Guest User

Untitled

a guest
Jun 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. public class Foo {
  2.  
  3. private static final instance = new Foo();
  4.  
  5. private final Object barGetterLock = new Object();
  6. private Bar barObject = null;
  7.  
  8. private static Foo getInstance() {
  9. return instance;
  10. }
  11.  
  12. private Foo() {
  13. // ... something here ...
  14. }
  15.  
  16. // This is a thread-safe lazy getter
  17. public Bar getBarObject() {
  18. if (barObject == null) {
  19. synchronized (barGetterLock) {
  20. /* Please note that barObject == null is tested again
  21. * This way, we can be sure that bar object will not be
  22. * initialized twice.
  23. *
  24. * Using the synchronized block before the first if works,
  25. * too, but when barObject is yet constructed and initialized,
  26. * using the synchronized block there will just be slower and
  27. * not useful.
  28. */
  29. if (barObject == null) {
  30. // Create the bar object
  31. barObject = new Bar();
  32. // Initialize the bar object, if needed ...
  33. }
  34. }
  35. }
  36.  
  37. return barObject;
  38. }
  39.  
  40. }
Add Comment
Please, Sign In to add comment