Thread safety issues raised by ollections.synchronizedlist
Some containers are thread-safe (vector,concurrentlinkedqueue, etc.), others are not (list, etc.), use class
Like private static list<task> Taskqueue = Collections.synchronizedlist (new
Linkedlist<task> ()); The method can get an easy thread-safe state that is not thread-safe by itself, but be aware
Is that thread safety refers only to the function that it provides, such as Queue.add (obj), if it is used directly; Or
Queue.poll (obj); so we don't need to do any synchronization ourselves.
But if non-atomic operations, such as:
1. if (!queue.isempty ()) {
2. Queue.poll (obj);
3.}
Atomic operations are operations that are not interrupted by a thread-scheduling mechanism; Once started, it runs until the end, without any context switch (switch to another thread)
It is difficult to guarantee that the queue was not modified by another thread until IsEmpty () was called, poll ().
So for this situation, we still need to synchronize ourselves:
1. Synchronized (queue) {
2. if (!queue.isempty ()) {
3. Queue.poll (obj);
4.}
5.}
For Collections.synchronizedlist (New linkedlist<task> ()),
When iterating over the returned list, the user must manually synchronize on the returned list:
List List = Collections.synchronizedlist (new ArrayList ()); ... synchronized (list) {
Iterator i = List.iterator (); Must is in synchronized block while (I.hasnext ())
Foo (I.next ()); }
Thread Safety Collections.synchronizedlist