Created
October 10, 2017 14:39
-
-
Save killme2008/bbd9ea3cb9875691301b5dbfbbb58488 to your computer and use it in GitHub Desktop.
concurrent test for hashset on JDK8
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.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