From e75ec71b32d061b44fceff76549f7158276c2847 Mon Sep 17 00:00:00 2001 From: Andrew Steinborn Date: Mon, 17 Sep 2018 01:03:07 -0400 Subject: [PATCH] Improve native initialization logic This uses the double-check pattern as recommended in Effective Java. --- .../natives/util/NativeCodeLoader.java | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java b/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java index 2f07378c8..692df5375 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java +++ b/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java @@ -8,7 +8,7 @@ import java.util.function.Supplier; public class NativeCodeLoader implements Supplier { private final List> variants; - private Variant selected; + private volatile Variant selected; public NativeCodeLoader(List> variants) { this.variants = ImmutableList.copyOf(variants); @@ -17,25 +17,32 @@ public class NativeCodeLoader implements Supplier { @Override public T get() { if (selected == null) { - selected = select(); + selected = tryLoad(); } return selected.object; } - private Variant select() { - for (Variant variant : variants) { - T got = variant.get(); - if (got == null) { - continue; + private Variant tryLoad() { + synchronized (this) { + if (selected != null) { + return selected; } - return variant; + + for (Variant variant : variants) { + T got = variant.get(); + if (got == null) { + continue; + } + selected = variant; + return selected; + } + throw new IllegalArgumentException("Can't find any suitable variants"); } - throw new IllegalArgumentException("Can't find any suitable variants"); } public String getLoadedVariant() { if (selected == null) { - selected = select(); + selected = tryLoad(); } return selected.name; }