wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronized Collection Decorators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronized Collection Decorators " Watch "Synchronized Collection Decorators " New topic
Author

Synchronized Collection Decorators

Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 356
I got the following excerpts from Khalid Mughal, Collections and Maps chapter.

The following static factory methods from the Collections class can be utilized to create decorators that provide thread-safety for collections:



All threads must access the underlying collection through the synchronized view, otherwise, non-deterministic behavior may occur.

Example



In addition, for traversing a synchronized collection, the code for traversing the collection must be synchronized on the decorator:




My question is that, we have already created a syncDecorator collection object, then what is the need to used synchronized block for traversing the synchronized collection.


SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

My question is that, we have already created a syncDecorator collection object, then what is the need to used synchronized block for traversing the synchronized collection.


Iteration is not a synchronized operation even if the collection is synchronized using Collections.synchronized...().

When you ask for an iterator, the Collection has to provide an Iterator implementation that can be used to traverse the data structure. Since there is no access to the underlying implementation of the iterator, the traversal itself cannot be made thread safe. It is also not possible to obtain / release locks when the next value in an iterator are returned by the SynchronizedCollection(internal class that does the synchronization).

As a result, you are advised to synchronize traversal alone if thread safety is necessary. Other operations do not need synchronization, but do not take that literally. A synchronized collection, synchronizes its operations individually. Combined operations still need to be atomic.

Example: On the same collection
T1: Read Write Read
T2: Read Read Read


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 356
Deepak, Thanks for the response. One more question off the topic...Can you suggest me a good book on core java. So far I have read scjp 1.4 by khalid mughal and scjp 1.6 by kathy sierra. I want a book that can give me greater and deeper understanding of core java concepts.

Thanks in advance
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronized Collection Decorators