Since c is already synchronzied collection, and it's thus thread safe. But why do we have to use synchronized(c)
again for the iteration? Really confused. Thanks.
" It is imperative that the user manually synchronize on the returned collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection);
...
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext()) {
foo(i.next());
}
}
Failure to follow this advice may result in non-deterministic behavior. " http://docs.oracle.com/javase/6/docs/api/java/util/Collections.
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.
The main reason for this slowness is locking; synchronized collections lock the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping.
A synchronized block of code can only be executed by one thread at a time. Synchronization in Java is basically an implementation of monitors . When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method , the monitor belongs to the class.
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.
The most any synchronized
collection implementation could possibly do is to guarantee that each individual method call is synchronized. But iteration necessarily involves multiple separate method calls, so you, the user of the synchronized collection, have to synchronize on the whole iteration yourself.
For example, if you didn't synchronize on c
, the contents of the collection could change between i.hasNext()
and i.next()
-- it could even go from having elements to having no more elements, in which case i.next()
would fail.
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