I got it from K & B.
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.
Answer:
� 3 E is correct. Synchronizing the public methods is sufficient to make this safe, so F is false.
But I think If we use StringBuffer then also it may solve the problem as its methods are synchronized. That means, append method is synchronized , so it will acquire the lock on contents, so no two threads can access that object.
Kindly clear me where i went wrong?
Thanks,
Geeta Vemula