This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Collection synchronization question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Collection synchronization question" Watch "Collection synchronization question" New topic
Author

Collection synchronization question

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
For LinkedList, the J2SE API says

Note that this implementation is not synchronized. If multiple threads access a list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method.

Similar is stated for all the rest of the unsynchronized collections. But why does it say that the synchronization should be done by either synchronizing or the "encapsulating object" or the Collections.synchronizedXXX method? Why couldn't you just synchronize on the collection itself?

For example,

LinkedList l = session.getAttribute("shared list");
synchronized(l) {
l.remove(valueToRemove);
}

Thank you,
Yuriy
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
This leaves open the possibility for bugs for any code which doesn't synchronize on the list before working with it. Sure, you might say, "But I'll make sure I remember to synchronize." Indeed.

By wrapping the list with a synchronized version and only referencing that wrapper, you guarantee that every piece of code that touches the list is synchronized. Safety first.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

because sometimes the significant part of using the collection may not be the collection itself. Most of my collections are not synchronized because I access them within synchronized blocks that do a few other things. If the collection itself were also synchronized it would be redundant for me.
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
All right, thanks!

-Yuriy
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection synchronization question
 
Similar Threads
HashMap, lock + unlock
Vector and ArrayList
NX: Does HashMap.containsKey(key) lock on the collection?
ArrayList vs java.awt.List
Do I need synchronization here ?