jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer thread safe question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer thread safe question" Watch "StringBuffer thread safe question" New topic
Author

StringBuffer thread safe question

Wu Wen
Greenhorn

Joined: Oct 14, 2011
Posts: 27
I have two pieces of code, both are asking how to ensure that instances of the class can be safely used by multiple threads?

1.

The answer to this question is Synchronize both log() and getContents() will make this class thread-safe

2.

The answer to this question is
It can be made thread safe if StringBuilder is replaced by StringBuffer Or
It can be made thread safe if addMessage() and dumpMessage() methods are synchronized.

My question is why I can not replace StringBuilder with StringBuffer to make first class thread-safe ? Thanks
Emilio Rojas
Greenhorn

Joined: Nov 26, 2011
Posts: 6
Quick answer to class 1:

The first code isn't threadsafe because a second thread could append data to contents concurrently, so "contents" could look like that:

one thread:
"Millis:nameMessage\n"

two threads (thread one in bold style):
"Millis:nameMillis:Messagename\nMessage\n

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

is it not because in the second example you are working with a static copy of the data?
Tim Moores
Rancher

Joined: Sep 21, 2011
Posts: 2408
I would say the answer is in the title: for thread-safety, use a StringBuffer instead of a StringBuilder. That is, after all, their only (I think) difference.
O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

Tim Moores wrote:I would say the answer is in the title: for thread-safety, use a StringBuffer instead of a StringBuilder. That is, after all, their only (I think) difference.


I think he is asking why the answer did not recommend changing the type (in the first example) from StringBuilder to StringBuffer
 
wood burning stoves
 
subject: StringBuffer thread safe question