Java Reference
In-Depth Information
The second important point is that locking a class does not lock instance variables of that
class. This is demonstrated in Listing 4-7. Notice that the method lockTest is both static and
synchronized. This means that it achieves a lock on the Class object. Figure 4-6 shows that
locking a class does not lock objects of that class.
Listing 4-7. A Locking Example
1 public class ClassLockNotObjectLock {
2 public static void main(String args[]) {
3 lockTest();
4 }
5
6 public static synchronized void lockTest() {
7 ClassLockNotObjectLock clnoc = new ClassLockNotObjectLock();
8 System.out.println("Is the class object locked? " +
9 Thread. holdsLock(clnoc.getClass()));
10
11 System.out.println("Is the object instance locked? " +
12 Thread. holdsLock(clnoc));
13 }
14 }
Figure 4-6. Locking a class doesn't lock objects of that class.
Locking in JDK 5
JDK 5 includes several packages that provide the ability to lock and wait on conditions sepa-
rate from the synchronization and locking mechanisms described previously. These have
several benefits, including the ability to specify whether locking should be granted fairly
(remember that the methods described earlier make no guarantees about the order in which
threads will be granted—a thread that has only just started waiting could be notified before a
thread that has been waiting for a long time).
Search WWH ::




Custom Search