Last active
September 25, 2017 05:48
-
-
Save massakam/5726be965fff0a7bb8b3a6dd7e970e28 to your computer and use it in GitHub Desktop.
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
Removal failed | |
Removal failed | |
Removal failed | |
... | |
Removal failed | |
Removal failed | |
Removal failed | |
B: 494 | |
A: 534 |
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.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