NOTE
StringBuffer
1. What It Is: a thread-safe mutable string, essentially StringBuilder with synchronized methods. 2. Usage. 3. Implementation analysis: constructor, append, toString, and substring.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What It Is
A thread-safe, mutable string.
It is essentially StringBuilder with the synchronized keyword added.
2. How to Use It
public class TestStringBuilder
{
public static void main(String[] args) throws InterruptedException
{
StringBuffer stringBuffer = new StringBuffer();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5000; i++)
{
stringBuffer.append("aaaa");
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5000; i++)
{
stringBuffer.append("aaaa");
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(stringBuffer.toString());
System.out.println(stringBuffer.length() == 5000 * 2 * 4);// true
}
}
3. Implementation Analysis
3.1. Constructor
public final class StringBuffer// It is also final
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
public StringBuffer() {
// Just like StringBuilder, it calls AbstractStringBuilder's constructor
super(16);// The default capacity is 16 characters
}
}
abstract class AbstractStringBuilder implements Appendable, CharSequence {
char[] value;
int count;
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
}
3.2. append Method
// Modified with synchronized
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
3.3. toString
// Modified with synchronized
public synchronized String toString() {
if (toStringCache == null) {
toStringCache = Arrays.copyOfRange(value, 0, count);
}
return new String(toStringCache, true);
}
3.4. subString
public synchronized String substring(int start, int end) {
return super.substring(start, end);
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub