以下は簡単な Java プログラムです。「cnt」と呼ばれるカウンターがあり、インクリメントされてから「monitor」と呼ばれるリストに追加されます。「cnt」は複数のスレッドでインクリメントされ、値は複数のスレッドで「monitor」に追加されます。
メソッド「go()」の最後で、cnt と monitor.size() は同じ値になるはずですが、そうではありません。monitor.size() には正しい値があります。
コメント化された同期ブロックの 1 つをコメント解除し、現在コメント化されていないブロックをコメント化してコードを変更すると、コードは期待どおりの結果を生成します。また、スレッド カウント (THREAD_COUNT) を 1 に設定すると、コードは期待どおりの結果を生成します。
これは、複数の実コアを搭載したマシンでのみ再現できます。
public class ThreadTester {
private List<Integer> monitor = new ArrayList<Integer>();
private Integer cnt = 0;
private static final int NUM_EVENTS = 2313;
private final int THREAD_COUNT = 13;
public ThreadTester() {
}
public void go() {
Runnable r = new Runnable() {
@Override
public void run() {
for (int ii=0; ii<NUM_EVENTS; ++ii) {
synchronized( monitor) {
synchronized(cnt) { // <-- is this synchronized necessary?
monitor.add(cnt);
}
// synchronized(cnt) {
// cnt++; // <-- why does moving the synchronized block to here result in the correct value for cnt?
// }
}
synchronized(cnt) {
cnt++; // <-- why does moving the synchronized block here result in cnt being wrong?
}
}
// synchronized(cnt) {
// cnt += NUM_EVENTS; // <-- moving the synchronized block here results in the correct value for cnt, no surprise
// }
}
};
Thread[] threads = new Thread[THREAD_COUNT];
for (int ii=0; ii<THREAD_COUNT; ++ii) {
threads[ii] = new Thread(r);
}
for (int ii=0; ii<THREAD_COUNT; ++ii) {
threads[ii].start();
}
for (int ii=0; ii<THREAD_COUNT; ++ii) {
try { threads[ii].join(); } catch (InterruptedException e) { }
}
System.out.println("Both values should be: " + NUM_EVENTS*THREAD_COUNT);
synchronized (monitor) {
System.out.println("monitor.size() " + monitor.size());
}
synchronized (cnt) {
System.out.println("cnt " + cnt);
}
}
public static void main(String[] args) {
ThreadTester t = new ThreadTester();
t.go();
System.out.println("DONE");
}
}