Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Foo {
- private static final instance = new Foo();
- private final Object barGetterLock = new Object();
- private Bar barObject = null;
- private static Foo getInstance() {
- return instance;
- }
- private Foo() {
- // ... something here ...
- }
- // This is a thread-safe lazy getter
- public Bar getBarObject() {
- if (barObject == null) {
- synchronized (barGetterLock) {
- /* Please note that barObject == null is tested again
- * This way, we can be sure that bar object will not be
- * initialized twice.
- *
- * Using the synchronized block before the first if works,
- * too, but when barObject is yet constructed and initialized,
- * using the synchronized block there will just be slower and
- * not useful.
- */
- if (barObject == null) {
- // Create the bar object
- barObject = new Bar();
- // Initialize the bar object, if needed ...
- }
- }
- }
- return barObject;
- }
- }
Add Comment
Please, Sign In to add comment