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();
}
ArrayList, LinkedList, HashSet,LinkedHashset and TreeSet in Collection Interface and HashMap,LinkedHashMap and Treemap are all non-synchronized.
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.
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. (
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.
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