Monday, August 9, 2010

Multithreading: Logger.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 9, Question 8

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



A.   This class is already thread-safe

This class is not thread-safe unless some sort of synchronization protects the changing data.


B.   Replacing StringBuilder with StringBuffer will make this class thread-safe

Not correct because although a StringBuffer is synchonized internally, we call append() multiple times, and nothing would prevent two simultaneous log() calls from mixing up their messages.


C.   Synchronize the log() method only

Incorrect. If one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse. (You don’t want to call getString() on the StringBuffer as it’s resizing its internal character array.)


D.   Synchronize the getContents() method only

Incorrect. If one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse. (You don’t want to call getString() on the StringBuffer as it’s resizing its internal character array.)


E.   Synchronize both log() and getContents()

Correct. Synchronizing the public methods is sufficient to make this safe.


F.   This class cannot be made thread-safe

This class is not thread-safe unless some sort of synchronization protects the changing data.

No comments:

Post a Comment