Java.lang.StringBuffer Source Code Analysis

Source: Internet
Author: User

StringBuffer is a thread-safe, variable-sequence character array object that, like StringBuilder, inherits from the parent class Abstractstringbuilder. In a multithreaded environment, when the method operation must be synchronized, the methods within the StringBuffer are synchronized to achieve the same consistency as in single-threaded operations.

 Public Final classStringBufferextendsAbstractstringbuilderImplementsjava.io.Serializable, charsequence {//a cache is used to store the value returned by the last call to ToString, and the cache is emptied whenever StringBuffer is modified    Private transient Char[] tostringcache;  PublicStringBuffer () {Super(16); }     PublicStringBuffer (intcapacity) {        Super(capacity); }    //... more constructs, which provides a constructor that is consistent with the parent class, the constructor of the StringBuffer always calls the constructor of the parent class@Override Public synchronized intLength () {//returns the number of characters in a container        returncount; } @Override Public synchronized intCapacity () {//returns the size of the container        returnvalue.length; } @Override Public synchronized voidEnsurecapacity (intminimumcapacity) {//Make sure the container is large enough        if(Minimumcapacity >value.length) {expandcapacity (minimumcapacity); }} @Override Public synchronized voidTrimToSize () {//Change the size of the container to match the number of characters in the container        Super. TrimToSize (); }    //SetLength is modifying the StringBuffer, so set the Tostringcache to null     Public synchronized voidSetLength (intnewlength) {Tostringcache=NULL; Super. SetLength (Newlength); }    //The Append,insert method also has other methods that need to be synchronized to overwrite the parent class, synchronize the method with synchronized, and those that modify the StringBuffer, which need to set the Tostringcache to null first //The following insert methods do not use synchronized for synchronization, which explains that the synchronization of these methods is accomplished by invoking other StringBuffer methods .     PublicStringBuffer Insert (intDstoffset, charsequence s) {        //Note, synchronization achieved via invocations of other stringbuffer methods//After narrowing of S-specific type//Ditto for Tostringcache clearing        Super. Insert (Dstoffset, s); return  This; }        PublicStringBuffer Insert (intOffsetBooleanb) {//Note, synchronization achieved via invocation of stringbuffer insert (int, String)//After conversion of B to String by Super class method//Ditto for Tostringcache clearing        Super. Insert (offset, b); return  This; }     PublicStringBuffer Insert (intOffsetinti) {//Note, synchronization achieved via invocation of stringbuffer insert (int, String)//After conversion of I-String by super class method//Ditto for Tostringcache clearing        Super. Insert (offset, i); return  This; }     PublicStringBuffer Insert (intOffsetLongl) {//Note, synchronization achieved via invocation of stringbuffer insert (int, String)//After conversion of L-String by Super class method//Ditto for Tostringcache clearing        Super. Insert (offset, l); return  This; }     PublicStringBuffer Insert (intOffsetfloatf) {//Note, synchronization achieved via invocation of stringbuffer insert (int, String)//After conversion of F-String by Super class method//Ditto for Tostringcache clearing        Super. Insert (offset, f); return  This; }     PublicStringBuffer Insert (intOffsetDoubled) {//Note, synchronization achieved via invocation of stringbuffer insert (int, String)//After conversion of D-String by Super class method//Ditto for Tostringcache clearing        Super. Insert (offset, d); return  This; }     Public intindexOf (String str) {//Note, synchronization achieved via invocations of other stringbuffer methods        return Super. indexOf (str); }     Public intlastIndexOf (String str) {//Note, synchronization achieved via invocations of other stringbuffer methods        returnlastIndexOf (str, count); }    //This tostring method is important, if Tostringcache is null, the current value will be copied a new copy to it, otherwise return string (Tostringcache)     Public synchronizedString toString () {if(Tostringcache = =NULL) {Tostringcache= Arrays.copyofrange (value, 0, Count); }        return NewString (Tostringcache,true); }    //The following three methods are used to implement serialization and deserialization of StringBuffer    Private Static Finaljava.io.objectstreamfield[] Serialpersistentfields =    {        NewJava.io.ObjectStreamField ("Value",Char[].class),        NewJava.io.ObjectStreamField ("Count", Integer.type),NewJava.io.ObjectStreamField ("Shared", Boolean.type),}; Private synchronized voidWriteObject (java.io.ObjectOutputStream s)throwsjava.io.IOException {Java.io.ObjectOutputStream.PutField fields=S.putfields (); Fields.put ("Value", value); Fields.put ("Count", Count); Fields.put ("Shared",false);    S.writefields (); }    Private voidReadObject (java.io.ObjectInputStream s)throwsjava.io.IOException, classnotfoundexception {java.io.ObjectInputStream.GetField fields=S.readfields (); Value= (Char[]) Fields.get ("value",NULL); Count= Fields.get ("Count", 0); }

From the above source, stringbuffer the parent non-thread-safe method to overwrite the implementation of synchronization, it own a tostringcache cache, when the cache is empty, it is known that StringBuffer has been modified, This time the ToString method is called to get the most recent value modified.

Java.lang.StringBuffer Source Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.