| 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
|
 |
 |
|
|
subject: Collection synchronization question
|
|
|