将String类型引用标记为Volatile安全吗? [英] Is marking String type reference as Volatile safe?

查看:165
本文介绍了将String类型引用标记为Volatile安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些文章和文章,说我们不应该将Java对象声明为volatile,因为结果是,只有引用才变成volatile.以下是一些示例:

链接-1 链接2 链接3

Sonar的建议是非原始字段不应该是易失性的"",但是,它也表明所描述的问题涉及可变对象类似地,将可变对象字段标记为volatile意味着对象引用是易变的,但是对象本身不是'.

我的问题是:将Java String声明为volatile是否安全?

解决方案

由于 String 对象是不可变的,因此只有引用由诸如 = 的运算符修改+ = .因此,volatile对于 String 是安全的,因为它适用于引用本身.这也适用于其他不可变对象,就像适用于基元一样.

说明:

+ = 本身也不是线程安全的,即使在易失的 String 上也是如此,因为它不是原子的,并且由读取和写入组成.如果在读写之间影响 String 对象,则可能导致意外结果.虽然生成的 String 仍然有效,但它可能具有意外的值.特别是,某些更改可能会覆盖"其他更改.例如,如果您有一个 String ,其值为"Stack" ,并且一个线程尝试附加"Overflow" ,而另一个试图附加"Exchange" ,则可能只应用一项更改.这也适用于原语.如果您有兴趣,可以在此处找到有关此特定问题的更多详细信息(主要是在基元的上下文中).>

I've read some posts and articles saying that we shouldn't declare java objects as volatile, because as a result, only the reference becomes volatile. Here are some examples:

link-1 link-2 link-3

What Sonar suggests is 'Non-primitive fields should not be "volatile"', however, it also suggests that the problem described refers to mutable objects 'Similarly, marking a mutable object field volatile means the object reference is volatile but the object itself is not'.

My question is: is it safe to declare java String as volatile?

解决方案

Because String objects are immutable, only the reference is modified by operators like = and +=. Therefore, volatile is safe for String, as it applies to the reference itself. This applies to other immutable objects as well, just as it does to primitives.

Clarification:

+= itself is not thread-safe even on a volatile String, as it is not atomic and consists of a read followed by a write. If something affects the String object between the read and write, it may lead to unexpected results. While the resulting String will still be valid, it may have an unexpected value. In particular, some changes may "overwrite" other changes. For instance, if you have a String with the value "Stack " and one thread tries to append "Overflow" while the other tries to append "Exchange", there is a possibility that only one change will be applied. This applies to primitives as well. If you are interested, more details about this particular issue (mostly in the context of primitives) can be found here.

这篇关于将String类型引用标记为Volatile安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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