我試圖提高對調用期間發出的鎖定範圍的理解。瞭解同步的行爲
如:
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);
}
}
什麼是消除這種副作用?
如果您從* add *方法中刪除* synchronized *,那麼當您調用* makeSnapshot *時,您根本無法保證其他線程添加的所有項目都具有「快照」。因此,據我可以看到,消除* synchronized *調用的副作用是現在代碼被破壞了。除此之外,甚至有可能達到不一致的狀態...... –