Java Reference
In-Depth Information
Listing 4-2. Synchronizing a Method
public synchronized void myMethod() {
//code
}
Listing 4-3. Synchronizing on the this Reference Object
public void myMethod() {
synchronized (this) {
//code
}
}
Locking some object other than this can provide more concurrency than synchronizing
a method because it allows other blocks of code that are synchronized on different objects to
work concurrently. But efficiency, alas, is in the eye of the beholder. If an individual method
needs to obtain multiple locks, then the steps of locking and unlocking the multiple locks can
lead to more overhead than synchronizing the method.
In Listing 4-4, synchThisObjectExample is more efficient than synchAllLocksExample
because it doesn't have the overhead of locking and unlocking three times. If your object is
carefully constructed not to allow unsynchronized access to the resources you need to lock,
then synchronizing methods is probably the simpler approach.
Listing 4-4. Synchronization Example
1 public class SynchExample {
2
3 private Resource resourceOne = new Resource();
4 private Resource resourceTwo = new Resource();
5 private Resource resourceThree= new Resource();
6
7 public synchronized void synchThisObjectExample() {
8 resourceOne.value = -3;
9 resourceTwo.value = -2;
10 resourceThree.value = -1;
11 }
12
13 public void synchAllLocksExample() {
14 synchronized (resourceOne) {
15 resourceOne.value = -3;
16 }
17
18 synchronized (resourceTwo) {
19 resourceTwo.value = -2;
20 }
21
Search WWH ::




Custom Search