Witscale Test Center

12.3 Access to shared data/code with synchronization > 12.3.6 Synchronizing the static methods


12.3.6 Synchronizing the static methods

Static methods can be synchronized just the way instance methods are synchronized, using the synchronized keyword in their declaration. For instance if the class UtilityBillManager has a static method totalUtilityAccounts(), you can synchronize it as:

 

public static synchronized int totalUtilityAccounts () { }

 

Since static code can modify only the static data, you will protect a static data with synchronized keyword. We know that static data and methods have only one copy for all the objects of that class. Therefore, you only need one lock per class to synchronize static methods. Object locks are not required for static methods. Static methods use a class lock for synchronization. This special lock is also an object lock.  It is lock on an instance of java.lang.Class object. Note that every class loaded in JVM has a corresponding instance of java.lang.Class representing that class. The class lock is the lock on that instance of java.lang.Class and it is used to synchronize the static methods of the class.

 

@

The class lock and the synchronization of static methods do not have much importance for the exam.