Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronizing a Collection  RSS feed

 
bhaswar goswami
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all ,


i want to synchronize a List using
Collection.synchronizedCollection(Collection c) method .

according to the java doc, i have to do like this :


Collection c = Collections.synchronizedCollection(myCollection);
...
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}



can anybody tell me , i can directly synchronize any object by puting
it in the synchronize block , then what is the point of
calling the : synchronizedCollection(Collection c)
mathod .


Regards,
Bhaswar
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

The synchronized block is necessary if you want to do a sequence of operations while excluding other threads that want to access that same collection. Without the synchronized block, other threads could call the methods of the collection while you were iterating over it -- adding or removing objects, leading to incorrect results or errors.

If it weren't a synchronized collection, then that synchronized block would not stop other threads from calling the methods of the collection.
[ July 04, 2005: Message edited by: Ernest Friedman-Hill ]
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I rarely have been able to use synchronized collections. Its rare that you will syynchronize ONLY addition or removal from a collection. Even then I like to use synchronized blocks so its obvious when/where I am synchronizing.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!