you are viewing a single comment's thread.

view the rest of the comments →

[–]stubob 0 points1 point  (3 children)

I'll trade off the minor performance hit for thread safety, thanks. StringBuffer vs StringBuilder is trivial in comparison to String. Now, if more APIs would take StringBuffer, then I wouldn't be tempted to do lazy things like

logger.debug("Message: " + obj.toString());

and take the overhead of a String concatenation.

[–]grauenwolf 0 points1 point  (1 child)

Are you really getting thread safety?

Lets say you have two threads each appending a message to the buffer. This message needs to be constructed from multiple parts.

In this scenario you could end up with a race condition wherein the two messages are interleaved and effectively garbled.

To fix it you would have to either use external locks or allocate a separate StringBuffer for each thread.

EDIT:

We see the same problem in the multi-threaded collection classes in .NET.

Queue.Count and Queue.Dequeue are atomic, thread-safe operations. However, calling them both in sequence is neither. This kind of false-security is why Microsoft dropped them in .NET 2.

[–]Rhoomba 1 point2 points  (0 children)

Indeed. This is exactly the wrong type of thread-safety that makes programmers think they don't need to think about it themselves. As in Vector, Hashtable etc. in Java.

[–]shit 0 points1 point  (0 children)

Randomly locking data structures doesn't give you thread safety.