Potential StringBuffer to StringBuilder clean-up (where warranted)

Joel Borggren-Franck joel.franck at oracle.com
Thu May 10 04:55:10 PDT 2012


Hi,

"Tobias Frech" <tobias at frech.info> writes:

> Hi, 
> concerning the safety of replacing StringBuffers with StringBuilders:
> not only should these StringBuffers not escape the method they are
> created in. But also they should not be assigned to an instance or
> static field of the class in this method or any other method which is
> called from within that method. 

If you assign a StringBuffer to a field then it is escaping. In this
context escaping means getting out of the method it is a local variable
in.

There are many ways the StringBuffer can escape:

- By assignment to a field
- By using it as a parameter to a method/constructor
- With an exception that gets thrown
- By assign it to an array that isn't local and provably non-escaping
- By returning it

(there may be other ways I haven't thought of ...)

In some of this cases the StringBuffer could be proven to not escape by
further analysis but this is very easy to get wrong. So for this
purpose, if it has a chance of leaving the method the StringBuffer is a
local variable in, consider it as escaping.

Expanding a bit on this:

You have two cases:

1) The StringBuffer provably doesn't escape. In this case as others have
said, the conversion will be safe. Beware of aliasing, in general there
can be many references to the same StringBuffer, none of them can
escape.

2) Given that the StringBuffer can escape, the transformation isn't
automatically safe, but neither automatically unsafe. But in this case
the analysis gets much more complicated. It might not be worth the
effort. The VM is very good at reducing cost for locks used only by one
thread. So if your escaping StringBuffer doesn't require the
synchronization then you won't loose that much by having it synchronize
(but if you actually need it well then the conversion wasn't safe to
begin with).

As Mike wrote:

> On 4 May 2012 17:05, Mike Duigou <mike.duigou at oracle.com> wrote:

>>
>> I think that for the most part you have it covered by ensuring that
>> the StringBuffer instances are all ones that don't escape the method
>> in which they are created.
>>

Thanks to all the volunteers for getting involved in this!

/cheers
Joel


More information about the jdk8-dev mailing list