Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

java - Why do I need to synchronize a list returned by Collections.synchronizedList

i found this at dos.oracle.com

public static List synchronizedList(List list)

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());
  }

My question is : Why do i have to Synchronize the list to iterate it if Collections.synchronizedList(); is supposed to return an already synchronized list ?

Im just accesing the list in two threads: One Thread just add and the other thread to get and delete. What other classes you recommend to use for this scenario ?

Thanks for reading.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The list being synchronized only means that add, remove etc. operations are synchronized and therefore atomic. Iteration however is not and if a thread adds while another is iterating, you could get a ConcurrentModificationException.

By manually synchronizing your iteration block, you ensure that the list is not modified while iterating.

One alternative is to use a CopyOnWriteArrayList which provides an iterator that iterates over the list as it was known when the iteration started, regardless of subsequent modifications. That collection is however not very efficient if you need to change the content of the list very often.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...