In Java, a lock can be obtained on the instance of a class or on a class itself.
We use lock on a class to synchronize static methods instead of lock on an object. Assume I have a private static data member of a class say staticData which is protected by synchronized static method staticFoo. If two threads t1 and t2 try to enter this critical section - staticFoo, Java language provides support to make sure only one thread is in the critical section. But we cannot prevent thread t3 that operates on instance of that class and modifies private static data member staticData. This means the MT-Safe protection is lost.
The solution to this problem is more of a coding discipline not to access static data members directly in object instances of the class if static data members are protected by synchronized static methods. We cannot really enforce it. This reminds me of a famous statement "Design should be open for extension but closed for modification". This is not the case here. Can you associate this problem to Singleton?
Binary Search Tree
8 years ago