Is String s = “foobar” atomic?

2020-02-27 11:08发布

Is String s = "foobar"; atomic?

Assigning a object-reference should be, but I'm no really sure.

Thanks.

标签: java atomic
2条回答
▲ chillily
2楼-- · 2020-02-27 11:33

Yes. All reference assignments are atomic in java.

Just note that a composite statement like String s = new String("foobar") is not atomic, because it comprises of an object creation and then an assignment separately.

Also note that "assignments to long and double variables may not be atomic", from JLS-17.7

查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-27 11:34

Yes, but if you're worried about race conditions, you should at least be aware of 'synchronized' methods/blocks.

And note that this is not atomic because it contains two operations:

String s = string_a + string_b;
查看更多
登录 后发表回答