对于下面的代码,
public class ListHelper<E>{
public List<E> list =
Collections.synchronizedList(new ArrayList<E>());
.....
public synchronized boolean putIfAbsent(E x){
boolean absent = !list.contains(x);
if(absent){
list.add(x);
}
}
}
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.
在执行putIfAbsent
操作时,这(上面)是线程安全失败的原因吗?
最佳答案
这是错误的锁(在 ListHelper
上同步,而不是在 list
上同步),此外,由于 list
是公开发布的 - 它可以被访问任何拥有 ListHelper 对象指针的人。
将其设置为私有(private),并确保没有人可以直接访问它(除非通过您将提供的同步方法),并确保您在执行读取时也进行同步 - 这样您就可以了。
另一种方法是向读者提供列表的不可修改的副本。
关于java - 向现有线程安全类添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46701633/