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.
"Say you had the code
Each append is thread safe, but the lock could be release at any point meaning you could get [1] What makes it worse is that the JIT and JVM will attempt to hold onto the lock between calls in the interests of efficiency.[2]"[1] is weirdly worded, or even wrong (I don't think "the lock could be release at any point" is correct) but the sample result does make sense to me if there are multiple threads banging on it at once. StringBuffer's append methods are synchronized, but without external synchronization, multiple calls could be interleaved.
I don't recall ever having heard of [2] before, and my copy of Java Concurrency in Practice isn't immediately at hand.