java理解同步程序的行为
我试图提高对synchronized
调用期间发出的锁的范围的理解
例如:
class CopyOnReadList<T> {
private final List<T> items = new ArrayList<T>();
public void add(T item) {
items.add(item);
}
public List<T> makeSnapshot() {
List<T> copy = new ArrayList<T>();
synchronized (items) {
// Make a copy while holding the lock.
for (T t : items) copy.add(t);
}
return copy;
}
}
(代码亲切地从this excellent answer借用)
在这个代码片段中,一个线程可以调用add
,而另一个线程可以调用makeSnapshot
?。也就是说,由synchronized (items)
创建的锁是否会影响所有试图读取items
的操作,或者只影响那些通过makeSnapshot()
方法尝试的操作
最初的帖子实际上在add方法中使用了synchonized
锁:
public void add(T item) {
synchronized (items) {
// Add item while holding the lock.
items.add(item);
}
}
去掉这个有什么副作用
# 1 楼答案
当然——然后,其中一个方法可能会失败,并出现
ConcurrentModificationException
,或者列表的内容可能已损坏都不是。锁对对象
items
的行为没有任何影响,只对在其上进行snychroning的块或方法有影响,即确保没有两个线程可以同时执行这些块或方法中的任何一个