Guest User

Untitled

a guest
Jan 24th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. // Double-check idiom for lazy initialization of instance fields
  2. private volatile FieldType field;
  3.  
  4. private FieldType getField() {
  5. FieldType result = field;
  6.  
  7. if (result == null) { // First check (no locking)
  8. synchronized(this) {
  9. if (field == null) // Second check (with locking)
  10. field = result = computeFieldValue();
  11. }
  12. }
  13. return result;
  14. }
  15.  
  16. // VS
  17.  
  18. private FieldType getFieldFixed() {
  19. FieldType result = field;
  20.  
  21. if (result == null) { // First check (no locking)
  22. synchronized(this) {
  23. // Missing assignment above
  24. // Needs to reassing the field in case several threads
  25. // hit synchronized together and the first one initialized
  26. // the fields
  27. // If the 2nd check is done on the field,
  28. // all further threads return null as result never gets reassigned.
  29. result = field;
  30. if (result == null) // Second check (with locking), in the original code checking the field
  31. field = result = computeFieldValue();
  32. }
  33. }
  34. return result;
  35. }
Add Comment
Please, Sign In to add comment