Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Problem - Locks and conditions w/ Threads

Tags:

java

monitor

java.lang.IllegalMonitorStateException is what I get with a nasty stack trace.

final Condition[] threads = new Condition[maxThreads];
myclass()
{
for (int i =0; i<maxThreads; i++)
            threads[i] = mutex.newCondition();
}    
public void test()
{

mutex.lock();
   int id = threadCount;
   threadCount++;
mutex.unlock();
threads[id].await();
}

When I call test with multiple threads it generates the error above. It is caused by the await line. I am hesitant to used synchronized because I want all threads to be able to await.

like image 507
Joshua Enfield Avatar asked Aug 04 '26 17:08

Joshua Enfield


1 Answers

You can only call await WHILE you hold the lock on mutex. So the code should be:

mutex.lock();
try {
   // do your stuff
   threads[id].await();
} finally {
   mutex.unlock();
}

The reason I added the try / finally is to ensure that the lock is released even if you throw an exception.

It is probably also worth noting that you can only call signal on your conditions while holding the lock on mutex as well. You are able to get a lock on the mutex, even though you got a lock before calling await, because calling await causes the waiting thread to release its lock while it waits.

like image 163
Matt Wonlaw Avatar answered Aug 07 '26 06:08

Matt Wonlaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!