singleton usage using lock
I have a Singleton which i want to use as monitor in a synchronized block
pri开发者_JAVA百科vate static final Singleton instance new Singleton();
public synchronized myMethod()
{
synchronized(Singleton.class)
{
do something
}
}
Is their a difference between using the class or using the instance object as the monitor?
There is. Singleton.class will be accessible in any class where the Singleton class is visible, whereas the instance you create is private, and thus visible only to that particular class.
In general, it's a good practice to synchronize on a monitor that can only be entered by the classes that should be synchronizing on it.
精彩评论