String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
So StringBuffer methods are synchronized internally. The user doesn't have to worry about this, it just happens. Much like for Vector and Hashtable - and just as for those classes, there are still cases where you might need a synchronized block to span multiple method calls. Don't let "it's synchronized" give ytou too much false security.
Strings, on the other hand, are not synchronized at all. But since they're immutable, it doesn't matter. You can access an immutable instance without synchronization, no problem. (Though if the reference variable you're using is not final, then you might need to sync to avoid problems there, just like for any variable.)
Note that in JDK 1.5, there's a new class StringBuilder. This is just like StringBuffer except it's not synchronized. So it will be faster in cases where you're only accessing the builder with one thread (as is usually the case). If synchronization is needed, I often find it better to explicitly use sync blocks anyway.
"I'm not back." - Bill Harding, Twister
Joined: Jun 23, 2004
Hey, where do you find out about the new classes in 1.5? I know how to find out about stuff like Generics and Autoboxing, etc. Thx for the 411.
Joined: Jan 30, 2000
Well, JDK 1.5 is out in Beta 2 release now, so you can download it and check it out yourself. Here are several good links for learning what's different: