I checked a synchronizedSet and a normal set with threads. I wrote a program below.
package thread;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ThreadSafeCheck {
public static void main(String[] args) {
SyncList job = new SyncList();
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(job.set);
System.out.println("Normal :" + job.set.size());
System.out.println(job.synSet);
System.out.println("Synchronized :" + job.synSet.size());
}
}
class SyncList implements Runnable {
Set<Integer> synSet = Collections.synchronizedSet(new HashSet<Integer>());
Set<Integer> set = new HashSet<Integer>();
public void run() {
displaysynchronizedMap();
displayNormalMap();
}
private void displaysynchronizedMap() {
for (int i = 0; i < 50; i++) {
synSet.add(i);
}
}
private void displayNormalMap() {
for (int i = 0; i < 50; i++) {
set.add(i);
}
}
}
To my surprise, the kit allows for duplication. How is this possible? Someone please explain this.
source
share