Since StringBuffer is thread safe, it can be safely published. Consider the public constructor of StringBuffer ( sources ):
public StringBuffer() { super(16); }
where super(16) stands for this:
AbstractStringBuilder(int capacity) { value = new char[capacity]; }
where is the value declared as
char[] value;
QUESTION: How to publish a StringBuffer safely?
I have the following class:
public class Holder{ public final StringBuffer sb = new StringBuffer(); }
Can a publication be considered safe? I think he can’t.
final ensures that we see the new sb link value. But writing to the internal sb state inside AbstractStringBuilder(int capacity) not synchronized. Therefore, there is no order happens-before , which, in turn, means that reading from value occurred when sb.append(2); called sb.append(2); and writing to value in the racy constructor.
Can you help figure this out? Maybe I missed something ...
source share