Gap Buffer based AbstractStringBuilder implementation

Thomas Hawtin Thomas.Hawtin at Sun.COM
Sun Nov 22 21:50:02 UTC 2009


Osvaldo Pinali Doederlein wrote:

>     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.

You will need to look at the Java Memory Model (JMM) (which is not 
sequentially consistent (SC)) to understand why this sort of thing can 
never work without adding synchronized/volatile to String. You can 
synchronize StringBuffer as much as you like, but it still wont work.

Tom Hawtin



More information about the core-libs-dev mailing list