However javadoc says that the user has to use the synchronize block to avoid deadlock.
Instead of using this method and using the synchronize block on the original list object also we can avoid deadlock.
From java doc :
List list = Collections.synchronizedList(new ArrayList());
synchronized(list) { }
Instead of this :
List list = new ArrayList();
synchronized(list) { }
What is the use of the " Collections.synchronizedList " method?
Here is an excerpt from documentation regarding synchronizedList function:
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:
List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Failure to follow this advice may result in non-deterministic behavior.
They say that you must synchronize only when iterating over list using iterator.
There is nothing about deadlock.
Other access (not through iterator) is guaranteed to be thread safe without special synchronization,
but only when you access this list through list (reference) returned from this function, not through reference to backed (original) list.
You could also use classes from the java.util.concurrent.* package. Such as the CopyOnWriteArrayList. Then you don't need external synchronization because (most) use-case are covered by the class itself.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Thennam Pandian
Ranch Hand
Joined: Oct 11, 2005
Posts: 163
posted
0
Hi,
Thanks all for your replies.
My question is why should i use synchronized block while iterating the synchronized list ?
How about other operations? Are they thread-safe?
let say add method, If it is thread safe, what is the logic behind the method "Collections.synchronizedList"?
When you synchronize your List using that method, all of its direct methods (add, remove, size, clear, etc) will be fully synchronized. However, any combination of calls still isn't. This is exactly what the iteration process does - combine multiple calls. As an example, let's look at iterating without an Iterator:
Even though list.size() and list.get(i) are both synchronized, without extra synchronization it's still possible to add or remove elements while iterating. By synchronizing on the entire block you prevent this: