Avoid work in Optional.orElse() calls
Any code inside the orElse() will always be called, even if the result
isn't used because the optional is present. This is wasteful at a
minimum and can be actively harmful (as seen in [1]) because of side
effects or performance impacts. Fix that by replacing all orElse() calls
that create new instances or do non-constant work with a call to
orElseGet().
It would be nice if there were an ErrorProne checker for this, but one
doesn't exist yet.
[1] https://gerrit-review.googlesource.com/c/gerrit/+/417915/comment/0ea287cd_bfecb7f2/
Release-Notes: skip
Change-Id: I2d3d59da88cd04a2e589b7255fc0877719a57432
diff --git a/src/main/java/com/googlesource/gerrit/plugins/manager/repository/CorePluginsRepository.java b/src/main/java/com/googlesource/gerrit/plugins/manager/repository/CorePluginsRepository.java
index 21e2a8d..2e175ea 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/manager/repository/CorePluginsRepository.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/manager/repository/CorePluginsRepository.java
@@ -77,13 +77,14 @@
"",
pluginUrl.toString());
})
- .orElse(
- new PluginInfo(
- dropSuffix(entryName.getFileName().toString(), ".jar"),
- "",
- "",
- "",
- pluginUrl.toString()));
+ .orElseGet(
+ () ->
+ new PluginInfo(
+ dropSuffix(entryName.getFileName().toString(), ".jar"),
+ "",
+ "",
+ "",
+ pluginUrl.toString()));
} catch (IOException e) {
logger.atSevere().withCause(e).log("Unable to open plugin %s", pluginUrl);
return null;
diff --git a/src/main/java/com/googlesource/gerrit/plugins/manager/repository/JenkinsCiPluginsRepository.java b/src/main/java/com/googlesource/gerrit/plugins/manager/repository/JenkinsCiPluginsRepository.java
index 2260a65..76254a6 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/manager/repository/JenkinsCiPluginsRepository.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/manager/repository/JenkinsCiPluginsRepository.java
@@ -119,7 +119,7 @@
Optional<SmartJson> buildExecution = tryGetJson(url + "/api/json");
Optional<JsonArray> artifacts =
buildExecution.map(json -> json.get("artifacts").get().getAsJsonArray());
- if (artifacts.orElse(new JsonArray()).size() == 0) {
+ if (artifacts.orElseGet(() -> new JsonArray()).size() == 0) {
return Optional.empty();
}