import java.util.*;
public class SyncTester {
public static void main(String[] args) {
final int SIZE = 100000;
final Random getterRandom = new Random(432987432987432L);
final Random putterRandom = new Random(564165098897163L);
// これは同期化されていないので破綻する。
final Map map = new HashMap(10, 0.1F);
// もしこっちを使うと同期化されているので正常に動作する。
// final Map map = Collections.synchronizedMap(new HashMap(10, 0.1F));
// デバッグ用に、put したキーを覚えておくための補助。
final Set synchronizedSet = Collections.synchronizedSet(new HashSet());
Runnable getterRunnable = new Runnable() {
public void run() {
while (true) {
int randomInt = getterRandom.nextInt(SIZE);
Integer key = new Integer(randomInt);
if (!synchronizedSet.contains(key)) {
continue;
}
Object value = map.get(key);
if (value == null) {
System.out.println("key = " + key + ", value = " + value);
throw new IllegalStateException();
}
}
}
};
Runnable putterRunnable = new Runnable() {
public void run() {
while (true) {
int randomInt = putterRandom.nextInt(SIZE);
Integer key = new Integer(randomInt);
Integer value = new Integer(randomInt);
if (!synchronizedSet.contains(key)) {
map.put(key, value);
synchronizedSet.add(key);
}
}
}
};
Thread getterThread = new Thread(getterRunnable);
getterThread.start();
Thread putterThread = new Thread(putterRunnable);
putterThread.start();
}
}
|