Skip to content

Instantly share code, notes, and snippets.

@massakam
Last active September 25, 2017 05:48
Show Gist options
  • Save massakam/5726be965fff0a7bb8b3a6dd7e970e28 to your computer and use it in GitHub Desktop.
Save massakam/5726be965fff0a7bb8b3a6dd7e970e28 to your computer and use it in GitHub Desktop.
Removal failed
Removal failed
Removal failed
...
Removal failed
Removal failed
Removal failed
B: 494
A: 534
import java.util.ArrayList;
import java.util.List;
import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
public class ThreadTest {
private static final int NUM_THREADS = 100;
private static ConcurrentOpenHashMap<String, List<Object>> map = new ConcurrentOpenHashMap<>();
private static class Updater extends Thread {
private static final int NUM_TRIALS = 1000;
@Override
public void run() {
for (int i = 0; i < NUM_TRIALS; i++) {
String key = i % 2 == 0 ? "A" : "B";
Object obj = new Object();
if (!map.computeIfAbsent(key, k -> new ArrayList<>()).add(obj)) {
System.out.println("Addition failed");
}
if (map.containsKey(key)) {
if (!map.get(key).remove(obj)) {
System.out.println("Removal failed");
}
} else {
System.out.println(key + " key is not contained");
}
}
}
}
public static void main(String[] args) throws Exception {
Updater[] threads = new Updater[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Updater();
threads[i].start();
}
for (int i = 0; i < NUM_THREADS; i++) {
threads[i].join();
}
for (String key : map.keys()) {
System.out.println(key + ": " + map.get(key).size());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment