Skip to content

Instantly share code, notes, and snippets.

@jhalterman
Created April 17, 2015 00:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhalterman/904e8aba0f38797c4bd7 to your computer and use it in GitHub Desktop.
Save jhalterman/904e8aba0f38797c4bd7 to your computer and use it in GitHub Desktop.
Double-checked lock pattern in Java 8
public static <T> T getWithDcl(Supplier<T> supplier, Supplier<T> factory, Object mutex) {
T object = supplier.get();
if (object == null) {
synchronized (mutex) {
object = supplier.get();
if (object == null) {
object = factory.get();
}
}
}
return object;
}
// Usage
Locks.getWithDcl(() -> pool.poll(), () -> factory.apply(this), pool);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment