競合状態を強制しようとした (または少なくともその発生確率を上げようとした) テストを作成しようとしましたが、CountDownLatch
.
問題は、私java.lang.IllegalMonitorStateException
がCountDownLatch.wait()
. 私は確かに を誤用してCountDownLatch
おり、このテストを巧妙な方法で作成していません。
この単純なコードは、私のアイデアと私の問題を再現します (私には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();
}
}
}
}
の javadoc には、現在のスレッドがオブジェクトのモニターの所有者でない場合にスローCountDownLatch.wait()
されることが記載されています。IllegalMonitorStateException
しかし、私はこれが何を意味するのか理解できず、この例外を回避するためにコードを再作成する方法を理解することもできません.
編集:回答に記載されているヒントを使用して、上記の例の新しいバージョンを作成し、この gistに保存しました。今は例外はありません。