Java Reference
In-Depth Information
Dealing with Nonimplicit Locking
You should be aware of two important issues when you deal with locks. First, locking an
object does not lock member variables of that object. This may seem counterintuitive at first,
but it makes sense from the JVM's point of view. Specifically, it allows the thread to avoid lock-
ing objects that may be nested n layers deep. Imagine the overhead of locking an object,
locking all of its member variables, locking all of their member variables, and so on. Listing 4-6
shows an example of locking objects but not their member variables. The output is shown in
Figure 4-5.
Listing 4-6. A Locking Objects Example
1 import java.util.*;
2
3 public class LockObjectNotMemberVariables{
4 private List myList = new ArrayList();
5
6 public static void main(String args[]){
7 LockObjectNotMemberVariables lonmv =
8 new LockObjectNotMemberVariables();
9 lonmv.lockTest();
10 }
11
12 public synchronized void lockTest(){
13 System.out.println("Is the THIS object locked? " +
14 Thread.holdsLock(this));
15
16 System.out.println("Is the list object locked? " +
17 Thread.holdsLock(myList));
18 }
19 }
Figure 4-5. Locking an object does not lock member variables of that object.
Search WWH ::




Custom Search