aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a synchronization question from the B SCJP 6 book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a synchronization question from the B SCJP 6 book" Watch "a synchronization question from the B SCJP 6 book" New topic
Author

a synchronization question from the B SCJP 6 book

Amelia Ma
Ranch Hand

Joined: Nov 09, 2009
Posts: 33
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!

Hi, this is Fat Louie. Please feel free to contact me at goFatLouie@yahoo.com
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Amelia Ma
Ranch Hand

Joined: Nov 09, 2009
Posts: 33
thank you very much for the reply. very clear.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a synchronization question from the B SCJP 6 book