String get / set threadsafe? [英] Is String get/set threadsafe?

查看:105
本文介绍了String get / set threadsafe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容,

public class Foo{
    private String bar;

    public String getBar(){
        return bar;
    }

    public void setBar(String bar){
        this.bar = bar;
    }
}

由于不可变的性质,这些方法是否自动线程安全 String 类,还是需要一些锁定机制?

Are these methods automatically threadsafe due to the immutable nature of the String class, or is some locking mechanism required?

推荐答案

否,这不是线程安全的。 Foo 是可变的,所以如果你想确保不同的线程看到 bar的相同值 - 即<强>一致性 - 要么:

No, this is not threadsafe. Foo is mutable, so if you want to ensure that different threads see the same value of bar – that is, consistency – either:


  • 制作 bar volatile ,或

  • 使方法同步,或

  • 使用 AtomicReference< String>

  • Make bar volatile, or
  • Make the methods synchronized, or
  • Use an AtomicReference<String>.

读取和写入 bar 本身就是原子的,但原子性不是线程安全。

The reads and writes of bar are themselves atomic, but atomicity is not thread safety.

http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

要深入报道Java并发,请获取 Java Concurrency in Practice(又名JCIP)

For in-depth coverage of Java concurrency, grab a copy of Java Concurrency in Practice (aka JCIP).

这篇关于String get / set threadsafe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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