Skip to content

Instantly share code, notes, and snippets.

@kencharos
Created August 23, 2013 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kencharos/6314754 to your computer and use it in GitHub Desktop.
Save kencharos/6314754 to your computer and use it in GitHub Desktop.
To check race condition about ConcurrentHashMap. if you use ConcurrentHashMap, you should atomic method. (e.g, putIfAbsent)
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentTest {
private static ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<Integer, Integer>();
private static class Update extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// forrowing code is incorrect. (probabry happens race condition)
if (!map.contains(i)) {
map.put(i, i);
System.out.println("puted [" + i + "] by " + getName());
}
// fix to map.putIfAbsent(i, i);
}
}
}
public static void main(String[] args) {
Update t1 = new Update();
Update t2 = new Update();
t1.start();
t2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment