我试图创建一个测试,我试图强制竞争条件(或至少增加其发生的可能性)并且我使用了CountDownLatch
.
问题是我java.lang.IllegalMonitorStateException
在我的CountDownLatch.wait()
. 我当然在滥用,CountDownLatch
而且我肯定不会以聪明的方式创建这个测试。
这个简单的代码重现了我的想法和我的问题(我也有一个要点):
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();
}
}
}
}
如果当前线程不是对象监视器的所有者,则抛出的CountDownLatch.wait()
状态的 javadoc 。IllegalMonitorStateException
但恐怕我不明白这意味着什么,我也无法弄清楚如何重新创建我的代码来避免这个异常。
编辑:根据答案中提供的提示,我创建了上面示例的新版本,并将其存储在这个 gist中。我现在没有任何例外。