News for hackers. Stuff that matters.
Re:Java memes which refuse to die by AYBABTME on Monday August 27, 2012 @11:54AM (#4439376)
I don't know if that's the answer you're looking for, but a call to append is synchronized:

    public synchronized StringBuffer append(/* Something */);
... but chaining them doesn't mean that the chain is synchronized.

   sb.append(key).append("=").append(value).append(", ");
is executed the same way as

   sb.append(key);
   sb.append("=");
   sb.append(value);
   sb.append(", ");
Two concurrent threads running this part of code might do this:

   sb.append(key);   // # 1
   sb.append("=");   // # 2
   sb.append(value); // # 3
   sb.append(", ");  // # 4

   // Thread 1 executes #1
   // Thread 2 executes #1
   // Thread 1 executes #2
   // Thread 1 executes #3
   // Thread 2 executes #2
   // Thread 2 executes #3
   // Thread 2 executes #4
   // Thread 1 executes #4
This can be executed in many more different ways.

To ensure that only one thread executes those `append` at once, you would have to synchronize on the `StringBuffer` instance:

    synchronize(sb){
        sb.append(key).append("=").append(value).append(", ");
    }
Then only one thread will do the appending at a time. But this introduce yet another lock in your code, and render the `synchronized` methods useless and redondant.
Re:Java memes which refuse to die by spacemanaki on Monday August 27, 2012 @12:41PM (#4439604)
Thanks, I looked up the source and saw that append was synchronized too. I was mostly asking about this claim from the OP: "the JIT and JVM will attempt to hold onto the lock between calls in the interests of efficiency". I don't think that's true.