Skip to content

Instantly share code, notes, and snippets.

@trasa
Created August 30, 2018 20:32
Show Gist options
  • Save trasa/31d04f50049bacd9bfbeebb1082d914c to your computer and use it in GitHub Desktop.
Save trasa/31d04f50049bacd9bfbeebb1082d914c to your computer and use it in GitHub Desktop.
public class VolatileDoubleCheck {
private final Object resourceLock = new Object();
private volatile Resource resource; // the thing we want to make sure we only have 1 of, marked as volatile
public Resource getResource() {
if (resource == null) {
synchronized(resourceLock) {
if (resource == null) {
resource = new Resource();
}
}
}
return resource;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment