Sometimes the below code throws IllegalStateMonitorException and sometimes it runs nicely. Not able to understand the scenarios how could it happen as it is always called under lock.lock().
Full Code:
public class OddEvenPrinter implements Runnable {
private Lock lock = new ReentrantLock();
Condition conditionFlag = lock.newCondition();
private int counter = 0;
public void run(){
for(int i = 0; i<1000;i++){
printEven();
printOdd();
}
}
private void printEven() {
try{
lock.lock();
while(counter%2!=0){
wait();
}
System.out.println(Thread.currentThread().getName()+" thread printing Even :"+counter);
counter++;
conditionFlag.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
private void printOdd(){
try{
lock.lock();
while(counter%2==0){
wait();
}
System.out.println(Thread.currentThread().getName()+" thread printing Odd :"+counter);
counter++;
conditionFlag.signalAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
OddEvenPrinter counter = new OddEvenPrinter();
Thread t1 = new Thread(counter);
Thread t2 = new Thread(counter);
t1.setName("First");
t2.setName("Second");
t1.start();
t2.start();
t1.join();
t2.join();
}
}