Skip to content

Instantly share code, notes, and snippets.

@devinrsmith
Last active June 29, 2020 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devinrsmith/17a03da0a408aaccceef to your computer and use it in GitHub Desktop.
Save devinrsmith/17a03da0a408aaccceef to your computer and use it in GitHub Desktop.
Double Checked Locking made easy with Java 8 Suppliers
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;
}
}
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