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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With