Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Double-check idiom for lazy initialization of instance fields
- private volatile FieldType field;
- private FieldType getField() {
- FieldType result = field;
- if (result == null) { // First check (no locking)
- synchronized(this) {
- if (field == null) // Second check (with locking)
- field = result = computeFieldValue();
- }
- }
- return result;
- }
- // VS
- private FieldType getFieldFixed() {
- FieldType result = field;
- if (result == null) { // First check (no locking)
- synchronized(this) {
- // Missing assignment above
- // Needs to reassing the field in case several threads
- // hit synchronized together and the first one initialized
- // the fields
- // If the 2nd check is done on the field,
- // all further threads return null as result never gets reassigned.
- result = field;
- if (result == null) // Second check (with locking), in the original code checking the field
- field = result = computeFieldValue();
- }
- }
- return result;
- }
Add Comment
Please, Sign In to add comment