StringBuilding optimization bug since Java 7 update 4

Skip Balk jgo at
Thu Jun 21 14:39:23 PDT 2012

Dear HotSpot developers,

This is the first time I post anything on any mailinglist, so please forgive me if my message is not quite up to the standards you are used to.

Last week, I encountered a bug in simple String concatenation, like:

String s = "test";
    s = s+s;
    s = s+s;
    s = s+s;

yielding the string: "nullnulltesttest" instead of "testtesttesttesttesttesttesttest". The first Java version that seems to suffer from this bug is Java 7u4, and is confirmed to occur in 7u5, 7u6(rc). It has been further reproduced on 32bit, 64bit, clientvm and servervm.

After a few thousand (interpreted) runs of this code, it starts to give these incorrect results, leading me to assume that a HotSpot optimisation is the root cause of this problem, which is backed by the fact that when running the java process with the -Xint argument, the bug does not occur.

Unfortunately, today I discovered that with my trivial sourcecode, the issue only occured with the Eclipse compiler. The Javac output seemed to be 'friendly' to HotSpot.

Upon further investigation, it turned out that "s=s+s" was compiled to different bytecode by Javac and Eclipse:
    Eclipse: s = new StringBuilder(String.valueOf(s)).append(s).toString();
    Javac:   s = new StringBuilder().append(s).append(s).toString();
When writing the version Eclipse produces in Java sourcecode, the javac compiler also produced the bytecode that made HotSpot trip.

Without further ado: here are the full code-dumps (both for eclipse and javac)

"javap -c" output, with sourcecode containing "s=s+s"

Console output:
    Java Version: 23.0-b21
    Failed at iteration: 11983
    Length mismatch: 16 <> 32
    Expected: "testtesttesttesttesttesttesttest"
    Actual:   "nullnulltesttest"

Last but not least, this bug seems to be triggered by the empty-for-loop, which leads me to believe this is a case of too aggresive dead code removal. I hope you can 

With kind regards,
    Riven ( administrator)
-------------- next part --------------
An HTML attachment was scrubbed...

More information about the hotspot-compiler-dev mailing list