Skip to content

Instantly share code, notes, and snippets.

@rvprasad
Last active December 18, 2021 22:17
Embed
What would you like to do?
Illustrates the absence of thread safety between various methods of SychronizedSet and its iteraror method.
Collection<Integer> ss = Collections.synchronizedSet(new HashSet<Integer>());
new Thread() {
public void run() {
for (int x = 0; x < 1000; x++) {
ss.addAll(IntStream.range(x*1000, (x + 1)*1000)
.boxed()
.collect(Collectors.toList()));
}
}
}.start()
for (int x = 0; x < 10; x++) {
Collection<Integer> t = new HashSet<Integer>(ss);
// Fix
//Collections.addAll(new HashSet<Integer>(), ss.toArray(new Integer[0]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment