Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer thread safe question

 
Wu Wen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it not because in the second example you are working with a static copy of the data?
 
Tim Moores
Bartender
Posts: 2895
46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic