StringBuffer.substring sharing

Bryce McKinlay bryce@mckinlay.net.nz
Wed Sep 24 09:54:00 GMT 2003


After I checked in Ralph Loader's fix for StringBuffer.substring the 
other day, Ralph pointed out that my modification had changed the 
meaning of the patch slightly:

On Monday, Sep 22, 2003, at 20:45 Pacific/Auckland, Ralph Loader wrote:

> My interpretation of the original code was that it was meant to prevent
> the possibility that a small substring of a large StringBuffer would
> prevent the large array being gc'd.
>
> The patch you checked in breaks this.  Consider:
>
> String Foo()
> {
>   StringBuffer b = new StringBuffer();
>   ... put a megabyte of stuff into b ...
>   String ignored = b.toString(); // sets b.shared
>   return b.substring (0, 1);
> }
>
> The 1 character String returned from Foo now has it's contents stored 
> in
> a megabyte char[], and that array has no other references.
>
> Passing ((len << 2) >= value.length) rather than StringBuffer.shared to
> the String constructor prevented this.

Its hard to say what is optimal here, as you can also argue that if the 
string is already shared then its reasonable to share even if the 
substring is small. However, having to copy a small string 
unnecessarily doesn't seem as bad as potentially wasting a lot of 
memory in the scenario above. So, I'm checking in the following patch, 
which reverts to the behaviour of Ralph's original patch.

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: StringBuffer2.patch.txt
URL: <http://gcc.gnu.org/pipermail/java-patches/attachments/20030924/47566662/attachment.txt>
-------------- next part --------------


Regards

Bryce.



More information about the Java-patches mailing list