Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized Collection Decorators

 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic