How does synchronized work in Java, and what is the difference between a synchronized method and a synchronized block?
The keyword synchronized makes a piece of code run by only one thread at a time, and the thing that they all wait for is called the monitor.
When you mark a method as synchronized, the lock that is taken is the object that the method belongs to. For an ordinary method, that is the object itself, which is written this. For a static method, it is the class object of the class that declared it, and every instance of that class shares that one lock.
A synchronized block lets you choose the lock yourself, because you write the object inside the brackets.
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Runnable task = new Runnable() {
public void run() {
for (int index = 0; index < 1000; index++) {
counter.increment();
}
}
};
Thread first = new Thread(task);
Thread second = new Thread(task);
first.start();
second.start();
try {
first.join();
second.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("the count : " + counter.getCount());
}
}
class Counter {
private int count;
// The lock is this object.
public synchronized void increment() {
this.count = this.count + 1;
}
public synchronized int getCount() {
return this.count;
}
}
So what is the difference between a synchronized method and a synchronized block? The lock that they take is different, and that is the whole difference.
A synchronized method takes the lock of the object, and it holds it for the whole method. A synchronized block takes the lock of the object that you name, and it holds it only for the part inside the braces. So a synchronized block is usually better, because it keeps the lock for a shorter time and it lets you lock on a private object that nothing else can reach.
The next question in this topic looks at what the monitor really is.