im trying to implement producer consumer using ReentrantLock in java
Condition producerlock = lock.newCondition();
Condition consumerlock = lock.newCondition();
it has two conditions one for producer and another for consumer .
Here we have a processor class with two methods producer consumer and one stack
Stack<Integer> hellostrack = new Stack<>();
public void produce() throws InterruptedException {
lock.tryLock();
System.out.println("inside producer method");
while (true) {
try {
if (hellostrack.size() > 8) {
System.out.println("stack is full its time for me to go to sleep");
producerlock.await();
}
System.out.println("thread is alive and kicking");
hellostrack.add(new Random().nextInt());
consumerlock.signalAll();
} finally {
System.out.println("Exception occours in producer Thread");
lock.unlock();
}
}
}
public void consume() throws InterruptedException{
System.out.println("inside consumer method");
lock.tryLock();
try {
while (true) {
if (hellostrack.isEmpty()) {
System.out.println("stack is empty im going to sleep");
consumerlock.await();
} else {
System.out.println("poping elelmts from stock" + hellostrack.pop());
consumerlock.signalAll();
}
} }finally {
System.out.println("Exception occours at consumer");
lock.unlock();
}
}
as you can see when stack reaches a certain limit producer will go to sleep , same for consumer when stack is empty
but when i run them in two thread
Processor p = new Processor();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
p.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t12 = new Thread(new Runnable() {
@Override
public void run() {
try {
p.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t12.start();
i get illegal state exception
inside consumer method
stack is empty im going to sleep
inside producer method
thread is alive and kicking
Exception occours in producer Thread
thread is alive and kicking
Exception occours in producer Thread
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.base/java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:149)
at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1302)
at java.base/java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:439)
at Processor.produce(Processor.java:30)
at Processor$2.run(Processor.java:76)
at java.base/java.lang.Thread.run(Thread.java:834)
poping elelmts from stock891164354
poping elelmts from stock-1958956829
stack is empty im going to sleep