What happens when a singleton object is pointing to a new reference?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyObject { | |
public static MyObject myObject = null; // Singleton object | |
private MyObject() { | |
} | |
// Only one instance of MyObject will ever exist, and this method must be called to grab it. | |
public synchronized static MyObject getInstance() { | |
if (myObject == null) { | |
myObject = new MyObject(); | |
} | |
// Set properties in myObject, then return it. | |
return myObject; | |
} | |
/* | |
The method above is equivalent to this one: | |
public static MyObject getInstance() { | |
synchronized (MyObject.class) { | |
if (myObject == null) { | |
myObject = new MyObject(); | |
} | |
return myObject; | |
} | |
} | |
*/ | |
public synchronized static MyObject doSomethingBad() { | |
// Create a new instance of MyObject, and then assign it to myObject. | |
myObject = new MyObject(); // BAD idea!!! myObject is now pointing to a new MyObject reference. | |
return myObject; | |
} | |
/* | |
If multiple threads are waiting to execute the doSomething() method (i.e., they are blocked | |
because another thread is in the middle of executing the method), they will block FOREVER if the | |
doSomethingBad() method executed successfully while they are waiting because the original | |
reference pointed to by myObject is overwritten, lost forever. Remember, adding the synchronized | |
keyword to a method is the same as: | |
synchronized (this) { | |
// critical section | |
} | |
and this refers to myObject, which should have been the only instance of MyObject ever created. | |
*/ | |
public synchronized void doSomething() { | |
// This method takes a while to execute. | |
} | |
public synchronized void doSomethingElse() { | |
// This method takes a while to execute too. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment