A9 Interview Question
Software Engineer in TestsCountry: United States
There exists only one copy of each method per class, be the method static or non-static. A thread needs to acquire the monitor of an appropriate object before entering a synchronized method which it releases when the thread returns from the method. In case of static synchronization the thread acquires the monitor of the class object, the locking is at class level so no other thread can execute it until the current thread releases the lock. In case of non-static synchronisation the thread acquires the monitor of that particular instance on which the call was made so other threads using different instances are not locked. They acquire monitors of there respective instances but continue to execute, as no two thread use the same instance.
Simple answer is it will never be thread safe if it is only static. Because static variables make sure that only one copy will be shared by all objects of that class, thats why static variable belongs to class. But it never says that static variables and methods will be thread safe. To make it thread safe, you have to use synchronize keyword over the Class object for that class.
- Ghosh September 13, 2014