• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a synchronization question from the B SCJP 6 book

 
Amelia Ma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the scenario: This class is intended to allow user to write a series of message, so that each message is identified with a time stamp and the name of the thread that wrote the message:

How can we ensure that instances of this class can be safel used by multiple threads?

the correct answer is Synchronize both log() and getContents()

I think if there is another choice: Replacing StringBuilder with StringBuffer and Synchronize log() will make this class thread-safe. It should also be a correct answer, right?

this is a problem from the KB scjp 6 book, chapter 9, page 764, problem 8.

Thanks!
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Making StringBuilder to StringBuffer won't make any difference as there are multiple calls to append method. Thus the thread safe behavior of StringBuffer won't help. So making log method synchronized is required (as you also said). But if we don't make getContents method synchronized, then we might get a partial result. Suppose if the log method is synchronized and getContents method is not. One thread calls the log method on a Logger object. The log method logs the current timestamp, and the colon (:) symbol. At the same time another thread calls getContents method on the same Logger object. That thread will get a partial record i.e. timestamp and colon but not the thread name and the message. Thus the answer in the book is right...
 
Amelia Ma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for the reply. very clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic