search

Home  >  Q&A  >  body text

java - String是线程安全的吗?那String岂不是不能进行同步?

  1. 我们知道不变对象是指一旦创建不能修改内部状态的对象,因为不变对象没有提供可供修改内部状态的方法,所以不变对象是线程安全的。但是String,当然包括其他的基本数据的包装类,如Integer/Long/Float等等,也是不变对象,但却是可以修改值的,这怎么保证线程安全?

public class Test{

private String str;

public void test(){
        if(("").equals(str)){  //多个线程同时判断,可能导致多次执行
            str = "1";
            //do something
        }
}

}

怪我咯怪我咯2767 days ago621

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:29:08

    Find another object that can be locked, lock it and then modify the String.

    private String lock = new Object();
    private String str;
    public void test(){
        synchronized(lock) {
            if(("").equals(str)){  //多个线程同时判断,可能导致多次执行
                str = "1";
                //do something
            }
        }
    }

    reply
    0
  • 阿神

    阿神2017-04-18 10:29:08

    In Java, String type objects themselves are immutable. Because String will be stored in a memory area called the constant pool.
    For example

            String a="test";
            String b="test";
            System.out.println(a==b);
            System.out.println(System.identityHashCode(a));
            System.out.println(System.identityHashCode(b));

    Output:

    true
    851664923
    851664923

    So why do you feel variable again?

    String a="test";
    a="test1"
    

    Then a becomes test1. In fact, a new "test1" string object is created here (if the constant pool does not have this value, it is newly created). Then point the variable reference to it. Note: The internal state of the "test" variable is not modified here. The "test" string object is thread-safe.
    Unless you modify it with final, all variables pointed to are mutable.
    Thread safety must be ensured in this case:
    No. 0: You can consider using volatile to ensure visibility.
    First, you can use final modification
    Second, you can use atomic objects such as AtomicReference, and for Integer, there are also AtomicInteger and the like
    Third, lock the corresponding code area

    reply
    0
  • Cancelreply