Gap Buffer based AbstractStringBuilder implementation

Osvaldo Pinali Doederlein opinali at
Sun Nov 22 19:23:59 UTC 2009

Em 22/11/2009 05:55, Thomas Hawtin escreveu:
> Osvaldo Doederlein wrote:
>> Looks like good stuff. And it remembers me from another old issue: 
>> patterns of code that demand data copying that could often be 
>> avoided. Every StringBuffer/StringBuilder is ultimately consumed by a 
>> toString() invocation to produce the result String, and in 99% of all 
>> uses, only one such String is produced and the buffer object is 
>> immediately discarded. So, toString() could pass the internal char[] 
>> to the String constructor, instead of forcing its copy. The API is 
>> coded conservatively to always do that copy, because in 1% of cases 
>> people 
> There is a security issue there. When multiple threads are involved, 
> it is possible (though not necessily easy) to create a mutable String 
> if the backing char[] is shared.
> Tom Hawtin

That's true. But there's apparently a simple solution

     public String toStringShared() {
         // createShared() is a package-protected helper/ctor
         String ret = String.createShared(value, 0, count);
         // Reset value, so evil user can't abuse the buffer to change 
the String.
         value = EMPTY;
         count = 0;
         return ret;
     private static final char[] EMPTY = new char[0];

This solution should be safe, without need of escape/alias analysis, 
because StringBuilder and StringBuffer don't have any methods that 
return a new mutable object that shares the same char[]. The only APIs 
that aliases the buffer is subSequence(), but this returns a 
CharSequence which is a read-only object.


More information about the core-libs-dev mailing list