• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is synchronizedCollection(..)..

 
Prashant Neginahal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
What is Collections.synchronizedCollection(Collection c).
Is it for making Collection Thread safe and as same as below,

synchronized(Collection c)
{
....
}
.....?
----------------
Prashant
 
Ellen Zhao
Ranch Hand
Posts: 581
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashant,
Only the Vector class out of the collection classes is thread-safe - that is, safe for modificaion by more than one thread. For the others you must either only access them by methods and code blocks that are synchronized on the collection object, or wrap the collection class in a thread-safe wrapper. The Collections class provides methods for creating synchronized sets, lists, and maps from unsynchronized objects. For example, the static synchronizedList() method in the collections class accepts an argument that is a list and returns a List object that is synchronized.

Ellen
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Prashant Neginahal:
Is it for making Collection Thread safe
It makes the collection threadsafe, but is unlikely to make your application threadsafe. You will use synchronized collections very, very rarely in practice; most of the time, you will have to synchronize your own methods.
Why? Synchronization makes operations atomic w.r.t. other threads. A synchronized collection makes the collection operations atomic -- set, get, add, remove... Most of the time, you need atomicity for larger operations than that, for example read-modify-write or contains-set. The fact that the little sub-operations are threadsafe buys you absolutely nothing in that case.
This is more a question for the Threads and Synchronization forum, by the way.
- Peter
[ December 30, 2002: Message edited by: Peter den Haan ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic