aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with thread question from K & B Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with thread question from K & B" Watch "Problem with thread question from K & B" New topic
Author

Problem with thread question from K & B

Herb Tybur
Greenhorn

Joined: May 12, 2006
Posts: 19

12. Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:

public class Logger {
private StringBuilder contents = new StringBuilder();
public void log(String message) {
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());
contents.append(message);
contents.append("\n");
}
public String getContents() { return contents.toString(); }
}


How can we ensure that instances of this class can be safely used by multiple threads?
A. This class is already thread-safe.
B. Replacing StringBuilder with StringBuffer will make this class thread-safe.
C. Synchronize the log() method only.
D. Synchronize the getContents() method only.
E. Synchronize both log() and getContents().
F. This class cannot be made thread-safe.


My answer was F but the correct answer is E. Even if you make both the methods synchronized, the following situation will totally mess the message up:

1. Thread 1 calls log("message");
2. Before thread 2 could do getContent(), thread 2 gets lock and calls log("message2"); This causes the message to contain "message1message2".
3. Thread 1 calls getContent()
4. Thread 2 calls getContent()

Basically, I feel that this class is structurally unsound and cannot be made thread safe.

Am I missing something?
Srinivas Bitla
Ranch Hand

Joined: Nov 10, 2003
Posts: 31
Hi Herb,

I didn't understand how does calls 1 thru 4 mess up the message? The calls seem to be perfectly fine to me.

Can you explain how it messes up the message?

Thanks,
Srinivas.
Herb Tybur
Greenhorn

Joined: May 12, 2006
Posts: 19
The getContent() method should return the same message that was logged. But in the situation that I gave it is giving difference values.

Thread 1 logged "message 1" but it is getting "message 1 message 2" back.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with thread question from K & B