Close

Java Collections - Collections.synchronizedSet() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <T> Set<T> synchronizedSet(Set<T> s)

Returns a synchronized (thread-safe) Set backed by the specified Set.


Examples


package com.logicbig.example.collections;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedSetExample {
private static AtomicInteger atomicInteger = new AtomicInteger();

public static void main(String... args) throws InterruptedException {
Set<Integer> set = new HashSet<>();
System.out.println("initial set size: " + set.size());

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
e.execute(() -> set.add(atomicInteger.incrementAndGet()));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(set.size());//should be 1000
}
}

Output

initial set size: 0
991




Using Collections.synchronizedSet:

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedSetExample2 {
private static AtomicInteger atomicInteger = new AtomicInteger();

public static void main(String... args) throws InterruptedException {
Set<Integer> s = new HashSet<>();
Set<Integer> set = Collections.synchronizedSet(s);
System.out.println("initial set size: " + set.size());

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
e.execute(() -> set.add(atomicInteger.incrementAndGet()));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(set.size());//should be 1000
}
}

Output

initial set size: 0
1000




See Also