Java“同步”关键字不禁止其他线程更改类成员的内部元素
我指的是JCP 4.4.2,它具有以下示例代码,
@ThreadSafe
public class ImprovedList<T> implements List<T>{
private final List<T> list;
public ImprovedList(List<T> list){this.list=list;}
public synchronized boolean putIfAbsent(T x){
boolean contains = list.contains(x);
if(contains){
list.add(x);
}
return !contains;
}
@Override
public synchronized void clear(){list.clear();}
}
该书说此改进清单是安全的,但是我有一个问题:
构造函数“列表”的输入参数来自外部。因此,尽管putifabsent()
是 on
rivevedlist
上的同步,但不能保证将锁定锁定在ReverVeList的内部元素上。列表
。如果另一个线程将任何类型[t]元素更改/添加到此list
,rivevevabsent.putifabsent
可能会导致未确定的状态。
请帮助纠正我的理解。
I'm referring to JCP 4.4.2 and it has following sample code
@ThreadSafe
public class ImprovedList<T> implements List<T>{
private final List<T> list;
public ImprovedList(List<T> list){this.list=list;}
public synchronized boolean putIfAbsent(T x){
boolean contains = list.contains(x);
if(contains){
list.add(x);
}
return !contains;
}
@Override
public synchronized void clear(){list.clear();}
}
The book said this ImprovedList is thread safe, but I have a question:
The input parameter of the constructor "list" is from outside. So, although putIfAbsent()
is synchronized
on ImprovedList
, there is no guarantee the lock is put on the internal elements of ImprovedList.list
. If another thread is changing/adding any type [T] element into this list
, ImprovedList.putIfAbsent
could result undetermined state, I guess.
Please kindly help to correct my understandings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,但是如果您看书,他们采取了这个假设:
此假设通过改进清单,代码为线程安全。
Yes exactly, but if you look in the book, they took this assumption:
Based on this assumption the code is thread-safe.