• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collection synchronization question  RSS feed

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All right, thanks!

-Yuriy
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!