Created
August 23, 2013 01:50
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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