Since StringBuffer
is thread safe it can safely be published. Consider the public constructor of StringBuffer
( sources ):
public StringBuffer() {
super(16);
}
where super(16)
designates this one:
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
where value declared as
char[] value;
QUESTION: How to publish StringBuffer
safely?
I've got the following class:
public class Holder{
public final StringBuffer sb = new StringBuffer();
}
Can it be considered as safe-publication? I think, it cannot.
final
guarantees that we'll see a fresh value of the reference sb
. But writing to the sb
's internal state within AbstractStringBuilder(int capacity)
is not synchronized. Therefore there's no happens-before
order which in turn means that read from value
occured when invoking sb.append(2);
and writing to value
in the constructor are racy.
Can you help to understand this? Maybe I missed something...
sb
to be an instance variable or should that be static? – ErmelindaermengardeAtomicReference<String>
. StringBuffer is for concurrent appending to it, a rare use-case. – Pembrokethis
from the constructor to something else and that doesn't happen inStringBuilder
. – HeterolysisStringBuffer
? This sounds like an XY problem. – Gourleyfinal
, right? – Educable