String为何称为不可变类

2018-11-15  本文已影响6人  sendos

什么是不可变类

不可变类:所谓的不可变类是指这个类的实例一旦创建完成后,就不能改变其成员变量值。如JDK内部自带的很多不可变类:Interger、Long和String等。
可变类:可变类就是该类生成的实例的成员变量等是可以被改变的,大多数类基本都是可变类。

不可变类的优势

不可变类最大的优势就是线程安全,因为触发线程不安全就是当一个变量是共享变量的时候,有多个线程同时访问该变量,并且去修改,则就会触发线程不安全。而不可变类由于内容已经不可变,只能读取,所以就不会出现线程安全问题。

不可变类的设计原则

String为何是不可变类

String的源码如下:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    /**
     * Class String is special cased within the Serialization Stream Protocol.
     *
     * A String instance is written into an ObjectOutputStream according to
     * <a href="{@docRoot}/../platform/serialization/spec/output.html">
     * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
     */
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];

    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }    

    void getChars(char dst[], int dstBegin) {
        System.arraycopy(value, 0, dst, dstBegin, value.length);
    }
    /** ......*/
}

可以看到,String的源码里面有很多个不可变的特点

上一篇下一篇

猜你喜欢

热点阅读