In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?
Code in the book:
public class IntBuffer
{
private int index;
private int[] buffer = new int[8];
// Function called by producer thread
public synchronized void produce(int num) {
while(index == buffer.length - 1) {
try { wait();}
catch(InterruptedException ex) {}
}
buffer[index++] = num;
notifyAll();
}
// Function called by consumer thread
public synchronized int consume() {
while(index == 0) {
try { wait();}
catch(InterruptedException ex) {}
}
int ret = buffer[--index];
notifyAll();
return ret;
}
}
No, they are the same.
private synchronized void foo() {}
private void foo2() {
synchronized(this){
}
}
They will do the exact same as both monitor the instance which they are called from.
A good tutorial can be found in the blog of Jakob Jenkov http://tutorials.jenkov.com/java-concurrency/synchronized.html#java-synchronized-example