Java“同步”关键字不禁止其他线程更改类成员的内部元素

发布于 2025-02-07 22:03:32 字数 778 浏览 1 评论 0原文

我指的是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]元素更改/添加到此listrivevevabsent.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫九 2025-02-14 22:03:33

是的,但是如果您看书,他们采取了这个假设:

改进清单假设一旦将列表传递给其构造函数,
客户将不会直接直接使用基础列表,访问
它仅通过改进清单

此假设通过改进清单,代码为线程安全。

Yes exactly, but if you look in the book, they took this assumption:

ImprovedList assumes that once a list is passed to its constructor,
the client will not use the underlying list directly again, accessing
it only via ImprovedList

Based on this assumption the code is thread-safe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文