Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 6 of 7
SynchronizationDemo2 demonstrates a synchronized instance method. However, you can also synchronize class methods. For example, the java.util.Calendar class declares a public static synchronized Locale [] getAvailableLocales() method. Because class methods have no concept of a this reference, from where does the class method acquire its lock? Class methods acquire their locks from class objects—each loaded
class associates with a Class object, from which the loaded class's class methods obtain their locks. I refer to such locks as class locks.
Caution: Don't synchronize a thread object's run() method because situations arise where multiple threads need to execute run(). Because those threads attempt to synchronize on the same object, only one thread at a time can execute run(). As a result, each thread must wait for the previous thread to terminate before it can access run().
Some programs intermix synchronized instance methods and synchronized class methods. To help you understand what happens in programs where synchronized class methods call synchronized instance methods and vice-versa (via object references), keep the following two points in mind:
The following code fragment illustrates the second point:
class LockTypes
{
// Object lock acquired just before execution passes into instanceMethod()
synchronized void instanceMethod ()
{
// Object lock released as thread exits instanceMethod()
}
// Class lock acquired just before execution passes into classMethod()
synchronized static void classMethod (LockTypes lt)
{
lt.instanceMethod ();
// Object lock acquired just before critical code section executes
synchronized (lt)
{
// Critical code section
// Object lock released as thread exits critical code section
}
// Class lock released as thread exits classMethod()
}
}
The code fragment demonstrates synchronized class method classMethod() calling synchronized instance method instanceMethod(). By reading the comments, you see that classMethod() first acquires its class lock and then acquires the object lock associated with the LockTypes object that lt references.
Despite its simplicity, developers often misuse Java's synchronization mechanism, which causes problems ranging from no synchronization to deadlock. This section examines these problems and provides a pair of recommendations for avoiding them.