java.util.Collections.SynchronizedList 中方法的实现是在互斥体上使用同步。既然所有的方法中,完整的方法体都在synchronized block 下,为什么不能写成synchronized方法呢?
基本上:
public boolean doSomething(Collection<?> coll) {
synchronized (mutex) {return c.doSomething(coll);}
}
对比
public synchronized boolean doSomething(Collection<?> coll) {
return c.doSomething(coll);
}
我没有扫描所有的类,但可能的原因是某些方法需要部分同步(即不是整个方法体),并且由于它们扩展了相同的基类(SynchronizedCollection),所以实现发生了使用互斥体来进行更精细的控制。那是对的吗?或者是否有任何其他原因(例如性能)选择这种实现?
最佳答案
why couldn't it be written as synchronized methods?
有一个package-private factory method for SynchronizedList
和 corresponding package-private constructor它允许使用列表本身以外的互斥体来构造列表。
你不能直接使用它,但在 java.util
包中会有它的用法。
SynchronizedList.subList
中有一个示例:
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return new SynchronizedList<>(list.subList(fromIndex, toIndex),
mutex);
}
}
即对子列表的访问在父列表上同步,而不是在子列表上同步。
另一个例子是Vector.subList
method :
public synchronized List<E> subList(int fromIndex, int toIndex) {
return Collections.synchronizedList(super.subList(fromIndex, toIndex),
this);
}
即对子列表的访问在 Vector
上同步,而不是在子列表上同步。
关于java - Collections.SynchronizedList 实现 - 同步方法与互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060886/