How do Synchronized Lists Work?

你说的曾经没有我的故事 提交于 2019-12-10 19:57:54

问题


I am not sure I understand Synchronized Lists in Java. Suppose I have the following:

 List<Integer> numbers = Collections.synchronizedList(new ArrayList<Integer>());

 // Assumption: This is running on a separate thread
 public void add() {
      numbers.add(new Random().nextInt(100));
 }

 // This is also running on a separate thread
 public void doSomething() {
      synchronized(numbers) {
           for (int i : numbers) {}
      }
 }

Basically, will the add() be able to add numbers to the list if doSomething() is invoked? What would happen if I instead used public synchronized void add() and public synchronized void doSomething()?

I am working on a UDP Socket Server, and I was going to store clients in an ArrayList. I would have multiple threads that can read, write, and modify this list. What should I be doing?


回答1:


will the add() be able to add numbers to the list if doSomething() is invoked?

No, not until the thread invoking doSomething() leaves the synchronized block.

What would happen if I instead used public synchronized void add() and public synchronized void doSomething()?

Assuming these are the only places where the list is used, the effect would be the same. But you would syncronize on the object containing the list rather than synchronizing on the list itself.

Basically, all the accesses to a shared state must be synchronized on the same lock. You choose the lock that you prefer. Instead of using a sychronized list, or synchronized methods, you could use a concurrent collection like a CopyOnWriteArrayList.




回答2:


This should work fine. According to the docs for Collections.synchronizedList, the list mutator methods (add(), etc.) synchronize on the list object itself. Since your iteration loop is also inside a synchronized block, all should be well.



来源:https://stackoverflow.com/questions/16780807/how-do-synchronized-lists-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!