最后的不可修改的线程是否安全? [英] Are final unmodifiable sets thread safe?

查看:150
本文介绍了最后的不可修改的线程是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于业余问题,很抱歉,由于 javadocs 不清楚这是我在想,是不可修改集线程安全?或者我应该担心内部状态并发问题吗?

Sorry for the amateur question, but since javadocs are not clear about this I was wondering, are unmodifiable sets thread safe? Or should I worry about internal state concurrency problems?

Set<String> originalSet = new HashSet<>();
originalSet.add("Will");
originalSet.add("this");
originalSet.add("be");
originalSet.add("thread");
originalSet.add("safe?");
final Set<String> unmodifiableSet = Collections.unmodifiableSet(originalSet);
originalSet = null; // no other references to the originalSet

// Can unmodifiableSet be shared among several threads?  

我偶然发现了一个静态的,只读的设置被多个线程共享...原作者写的像这样:

I have stumbled upon a piece of code with a static, read-only Set being shared against multiple threads... The original author wrote something like this:

mySet = Collections.synchronizedSet(Collections.unmodifiableSet(originalSet));

然后每个线程使用以下代码访问它:

And then every thread access it with code such as:

synchronized (mySet) {
  // Iterate and read operations
}

通过这个逻辑,只有一个线程可以立即操作Set ...
所以我的问题是,对于一个不可修改的集合,当使用操作如 包含 size 等,我真的需要同步访问吗? p>

By this logic only one thread can operate on the Set at once... So my question is, for a unmodifiable set, when using operations such as for each, contains, size, etc, do I really need to synchronize access?

推荐答案

如果它是一个不可修改的 Set< String> 那么你很好;因为 String 对象是不可变的。但是如果它是一组不可变的东西,你必须小心两个线程,尝试改变集合中的同一个对象。

If it's an unmodifiable Set<String>, as per your example, then you're fine; because String objects are immutable. But if it's a set of something that's not immutable, you have to be careful about two threads both trying to change the same object inside the set.

你还必须仔细考虑是否有一个引用 Set 的地方,这不是不可修改的。变量可以不可修改,但仍然指向可以通过不同变量修改的 Set ;但你的例子似乎有覆盖。

You also have to be careful about whether there's a reference somewhere to the Set, that's not unmodifiable. It's possible for a variable to be unmodifiable, but still be referring to a Set which can be modified via a different variable; but your example seems to have that covered.

这篇关于最后的不可修改的线程是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆