问题
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