Last active
June 29, 2020 03:45
-
-
Save devinrsmith/17a03da0a408aaccceef to your computer and use it in GitHub Desktop.
Double Checked Locking made easy with Java 8 Suppliers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.Supplier; | |
/** | |
* Created by dsmith on 2/16/15. | |
* | |
* https://en.wikipedia.org/wiki/Double-checked_locking | |
* | |
*/ | |
public class DoubleCheckedSupplier<T> implements Supplier<T> { | |
public static <T> Supplier<T> of(Supplier<T> supplier) { | |
return new DoubleCheckedSupplier<>(supplier); | |
} | |
private final Supplier<T> supplier; | |
private volatile T t; | |
private DoubleCheckedSupplier(Supplier<T> supplier) { | |
this.supplier = supplier; | |
} | |
@Override | |
public T get() { | |
// use of local variable so we can control number of volatile read / writes | |
T local = t; // vol read | |
if (local == null) { | |
synchronized (supplier) { | |
local = t; // vol read | |
if (local == null) { | |
local = supplier.get(); | |
if (local == null) { | |
throw new IllegalStateException("Supplier should not return a null result"); | |
} | |
t = local; // vol write | |
} | |
} | |
} | |
return local; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final Supplier<MyObject> MYOBJECT = DoubleCheckedSupplier.of(() -> new MyObject()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment