我正在阅读 B. Goetz Java 并发实践,现在我正在阅读向现有线程安全类添加功能的部分。他表示:
The synchronization policy of Vector is fixed by its specification, so BetterVector would not suffer from this problem.
@ThreadSafe
public class BetterVector<E> exends Vector<E>{
public synchronized boolean putIfAbsent(E x){
boolean absent = !contains(x);
if(absent)
add(x);
return absent;
}
}
所以,我试图弄清楚 Vector
的同步策略只能发现
Unlike the new collection implementations, Vector is synchronized.
是否意味着是通过这个对象同步的?或者它可能意味着任何(可能是私有(private))对象的同步。如果是这样,BetterVector<E>
非常脆弱,因为它取决于当前同步策略的实现,甚至没有明确指定。
最佳答案
这是一个非常好的问题。你是对的,Vector
的同步方式似乎没有被指定。 (至少,我找不到任何规范)。
但是,当前的实现在对象本身上同步,而不是在内部对象上同步。虽然这种实现可能随时改变,但这不太可能发生。太多代码可能依赖于当前的实现。改变可能会破坏所有事情。我怀疑代码维护者会冒这个风险。
我的猜测是,依赖于当前实现的代码理论上极其脆弱,但由于相当保守的代码维护和对 Java 开发过程的公共(public)监督,实际上几乎没有风险。
关于java - 了解 vector 同步策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34605131/