| Author |
Synchronizing a Collection
|
bhaswar goswami
Greenhorn
Joined: Jul 04, 2005
Posts: 14
|
|
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
|
Regards,
Bhaswar Goswami
SCJP 5.0 , SCDJWS
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
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 ]
|
[Jess in Action][AskingGoodQuestions]
|
 |
Mr. C Lamont Gilbert
Ranch Hand
Joined: Oct 05, 2001
Posts: 1170
|
|
|
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.
|
 |
 |
|
|
subject: Synchronizing a Collection
|
|
|