Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is synchronized Collection's toArray() method synchronized?

If I have a synchronized collection like this

Collection c = Collections.synchronizedCollection(myCollection);

javadoc for the synchronizedCollection mentiones that external iteration must be synchronized like this :

synchronized (c) {
 Iterator i = c.iterator();
 while (i.hasNext()) {
     process (i.next());
 }
}

Can I assume that c.toArray() is synchronized and therefore no changes to the collection will happen when the method executes?

Or do I need to synchronize it as well:

synchronized (c) {
  c.toArray();
}
like image 721
artur Avatar asked Feb 23 '12 13:02

artur


People also ask

Which collection methods are not synchronized?

ArrayList, LinkedList, HashSet,LinkedHashset and TreeSet in Collection Interface and HashMap,LinkedHashMap and Treemap are all non-synchronized.

Is ArrayList synchronized by default?

Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally.

What is synchronized and non-synchronized in Java?

A Synchronized class is a thread-safe class. Non-Synchronized means that two or more threads can access the methods of that particular class at any given time. StringBuilder is an example of a non-synchronized class. Generally, a non-synchronized class is not thread-safe. (


1 Answers

From the Javadoc for synchronizedCollection:

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

Thus, c.toArray() does not require any additional synchronization. SynchronizedCollection's toArray() method will do the locking for you. In essence, that's the whole point of synchronizedCollection().

If you want to confirm that this reading of the contract agrees with the actual implementation, see GrepCode.

like image 91
NPE Avatar answered Oct 13 '22 02:10

NPE