I tried to create a test where I tried to force a race condition (or at least to increase the probability of its occurrence) and I've used a CountDownLatch
.
The problem is that I get a java.lang.IllegalMonitorStateException
at my CountDownLatch.wait()
. I'm certainly misusing the CountDownLatch
and I'm surely not creating this test in a clever way.
This simple code reproduces my idea and my problem (I also have a gist):
import java.util.*;
import java.util.concurrent.*;
public class Example {
private static BusinessLogic logic;
public static void main(String[] args) {
final Integer NUMBER_OF_PARALLEL_THREADS = 10;
CountDownLatch latch = new CountDownLatch(NUMBER_OF_PARALLEL_THREADS);
logic = new BusinessLogic();
// trying to force the race condition
List<Thread> threads = new ArrayList<Thread>(NUMBER_OF_PARALLEL_THREADS);
for (int i=0; i<NUMBER_OF_PARALLEL_THREADS; i++) {
Thread worker = new Thread(new WorkerRunnable(latch));
threads.add(worker);
worker.start();
}
for (int i = 1; i <= NUMBER_OF_PARALLEL_THREADS; i++) {
try {
threads.get(i).wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Just a dummy business logic class.
* I want to "force" a race condition at the method doSomething().
*/
private static class BusinessLogic {
public void doSomething() {
System.out.println("Doing something...");
}
}
/**
* Worker runnable to use in a Thead
*/
private static class WorkerRunnable implements Runnable {
private CountDownLatch latch;
private WorkerRunnable(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
// 1st I want to decrement the latch
latch.countDown();
// then I want to wait for every other thread to
latch.wait(); // the exception is thrown in this line.
// hopefully increase the probability of a race condition...
logic.doSomething();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The javadoc of the CountDownLatch.wait()
states that the IllegalMonitorStateException
is thrown if the current thread is not the owner of the object's monitor. But I'm afraid I'm not understanding what this mean, nor I am able to figure how could I recreate my code to avoid this exception.
EDIT: with the tips provided in the answers, I've created a new version of the example above and I've stored in this gist. I don't have any exceptions now.