Skip to content

Instantly share code, notes, and snippets.

@killme2008
Created October 10, 2017 14:39
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 killme2008/bbd9ea3cb9875691301b5dbfbbb58488 to your computer and use it in GitHub Desktop.
Save killme2008/bbd9ea3cb9875691301b5dbfbbb58488 to your computer and use it in GitHub Desktop.
concurrent test for hashset on JDK8
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
public class HashSetTest {
private static Set<String> set = new HashSet<String>();
public static boolean update(final Set<String> subList) {
boolean updated = !set.equals(subList);
set.addAll(subList);
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String next = it.next();
boolean exist = subList.contains(next);
if (!exist) {
it.remove();
updated = true;
}
}
return updated;
}
public static void main(String[] args) throws Exception {
int threads = 10;
final CyclicBarrier barrier = new CyclicBarrier(threads + 1);
for (int i = 0; i < threads; i++) {
new Thread() {
public void run() {
try {
barrier.await();
Set<String> newSet = new HashSet<String>();
newSet.add("a");
newSet.add("b");
while (update(newSet)) {
System.out.println(set.size() + " " + set);
}
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
barrier.await();
barrier.await();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment