Get Synchronized Set from HashSet in Java

In this tutorial, we will learn about How to Get Synchronized Set from HashSet in Java ?

HashSet in Java extends AbstractSet and implements Set interface which is backed by hash table.  It creates a collection that uses a hash table for storage. This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits null element. HashSet is not synchronized . When we use HashSet in multithreading environment, it may be possible that each thread is either adding, updating or removing the records/entries which will lead to dirty reads.

To resolve this problem, we can synchronize HashSet in Java. Snchronization of HashSet will affect the performance and probably reduce the speed of HashSet as synchronized method is always slower than non-synchronized one.

Collections class in Java provides synchronizedSet() method to get synchronized Set. We can get synchronized Set from HashSet using this method.

Syntax of synchronizedSet() method:

set – the set to be wrapped in a synchronized Set.

a synchronized set.



Related posts

Leave a Comment