Skip to content

Instantly share code, notes, and snippets.

@Epsiloni
Created May 19, 2015 07:17
Show Gist options
  • Save Epsiloni/9f2be4bbf8ee1de10488 to your computer and use it in GitHub Desktop.
Save Epsiloni/9f2be4bbf8ee1de10488 to your computer and use it in GitHub Desktop.
For High-Performance on an Instance Field, Use the Double-Check Idiom
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) { // 1st check (no lock)
synchronized (this) {
result = field;
if (result == null) // 2nd check (w/ lock)
field = result = computeFieldValue();
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment