Java Reference
In-Depth Information
Synchronized Methods
A synchronized method is similar to a synchronized block of code except the lock being
acquired is on the object the synchronized method is invoked on. Think of a synchronized
method as a synchronized block of code that attempts to acquire the this reference. Use
the synchronized keyword in the method declaration to denote a method as synchronized.
Let's revisit the MyStack class from earlier in this section. The push and pop methods
are good candidates for synchronized methods because they perform atomic tasks.
The following version of the class, MyStack2 , demonstrates the syntax for declaring
synchronized methods:
public class MyStack2 {
private int [] values = new int[10];
private int index = 0;
public synchronized void push(int x) {
if(index <= 9) {
values[index] = x;
Thread.yield();
index++;
}
}
public synchronized int pop() {
if(index > 0) {
index--;
return values[index];
} else {
return -1;
}
}
public synchronized String toString() {
String reply = “”;
for(int i = 0; i < values.length; i++) {
reply += values[i] + “ “;
}
return reply;
}
}
All three methods of MyStack2 are declared as synchronized . This simple change to the
class now makes it thread-safe, and the issue of data corruption that existed in MyStack
Search WWH ::




Custom Search