Friday 15 August 2014

How to synchronize Set

Set is non-synchronized in Java. So to perform thread-safe operations,you must synchronize Set.

There are two ways.
   1. Synchronizing the set explicitly. 
   2. Use 'Collections.synchronizedSet' method.

import java.util.*;

public class SetEx {
    public static void main(String args[]){
        Set<Integer> mySet = Collections.synchronizedSet(new HashSet<> ());
        
        mySet.add(10);
        mySet.add(20);
        mySet.add(30);
        
        System.out.println(mySet);
    }
}

Output
[20, 10, 30]



                                                             Home

No comments:

Post a Comment