Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.synchronizedList and synchronized

List<String> list = Collections.synchronizedList(new ArrayList<String>()); synchronized (list) {     list.add("message"); } 

Is the block "synchronized (list){} " really need here ?

like image 577
romsky Avatar asked Feb 27 '12 16:02

romsky


1 Answers

You don't need to synchronize as you put in your example. HOWEVER, very important, you need to synchronize around the list when you iterate it (as noted in the Javadoc):

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());    } 
like image 57
Sam Goldberg Avatar answered Sep 22 '22 13:09

Sam Goldberg