JDK source series (5) -StringBuffer

I. Overview

StringBuffer is a thread-safe, mutable sequence of characters, with the String is similar, but it can be modified. StringBuffer can safely be used in a multi-threaded environment, because its methods are modified by the synchronized keyword. This ensures that any action will be executed in a serial manner.

Second, the common method

The main operation StringBuffer additional string is inserted and, at the end of the string is additionally added, and the insert method may be added at the specified location. It is noted that, the append operation and insert method, occur in a string buffer.

Class definition:

 public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence

StringBuffer will call the constructor AbstractStringBuilder initialized, a default capacity of 16:

    public StringBuffer() {
        super(16);
    }

    //抽象父类AbstractStringBuilder的实现,构造了一个字符串缓冲区
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

You can also pass the size of the capacity at the time of construction.

Construction time can pass a string or CharSequence, then its capacity is the length of the string or CharSequence +16.

append () methods are synchronous, then append call parent class () to determine the capacity, the additional operations performed.

There indexOf, reverse, toString method, etc., are synchronized.

Third, the serialization and de-serialization implementation StringBuffer

Private rely on the following three ways:

    private static final java.io.ObjectStreamField[] serialPersistentFields =
    {
        new java.io.ObjectStreamField("value", char[].class),
        new java.io.ObjectStreamField("count", Integer.TYPE),
        new java.io.ObjectStreamField("shared", Boolean.TYPE),
    };

    
    private synchronized void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        java.io.ObjectOutputStream.PutField fields = s.putFields();
        fields.put("value", value);
        fields.put("count", count);
        fields.put("shared", false);
        s.writeFields();
    }

    
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        java.io.ObjectInputStream.GetField fields = s.readFields();
        value = (char[])fields.get("value", null);
        count = fields.get("count", 0);
    }

IV Summary

StringBuffer class is relatively simple, the main implementation methods are implemented in a parent class, which itself is mainly done synchronous operation, it can also be concluded that there is no ready-made in an environment of security issues, is not recommended to use this class, but should go use StringBuilder class, the performance will be better.

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_37609579/article/details/103500201