Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a synchronized Collection?

Imagine a synchronized Collection:

Set s = Collections.synchronizedSet(new HashSet())

What's the best approach to clone this Collection?

It's prefered that the cloning doesn't need any synchronization on the original Collection but required that iterating over the cloned Collection does not need any synchronization on the original Collection.

like image 387
MRalwasser Avatar asked Jan 03 '11 13:01

MRalwasser


People also ask

How do you get a synchronized collection object?

Here are the detailed Steps: Create an ArrayList. Populate the arrayList with elements, with add(E e) API method of ArrayList. Invoke the synchronizedList(List list) API method of Collections to get the synchronized list from the provided ArrayList.

What is a synchronized collection?

The synchronizedCollection() method of java. util. Collections class is used to return a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.

Is CopyOnWriteArrayList synchronized?

CopyOnWriteArrayList is used to synchronize the ArrayList. The Java 1.2 version first introduced the Synchronized ArrayList. The Java 1.5 version first introduced the CopyOnWriteArrayList. The Synchronized ArrayList should be used when there are more write operations than reading operations in ArrayList.


1 Answers

Use a copy-constructor inside a synchronized block:

synchronized (s) {
    Set newSet = new HashSet(s); //preferably use generics
}

If you need the copy to be synchronized as well, then use Collections.synchronizedSet(..) again.

As per Peter's comment - you'll need to do this in a synchronized block on the original set. The documentation of synchronizedSet is explicit about this:

It is imperative that the user manually synchronize on the returned set when iterating over it

like image 195
Bozho Avatar answered Oct 06 '22 04:10

Bozho