aspose file tools
The moose likes Threads and Synchronization and the fly likes Synchronizing  a Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Synchronizing  a Collection " Watch "Synchronizing  a Collection " New topic
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
    
  13

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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Synchronizing a Collection
 
Similar Threads
Threads
about java.util.Collections
Collection question
servlet and thread synchronization
Iterating over Synchronized Map