How must this code be changed to be thread-safe?

Given:
1. public class MyLogger {
2. private StringBuilder logger = new StringBuuilder();
3. public void log(String message, String user) {
4. logger.append(message);
5. logger.append(user);
6. }
7. }
The programmer must guarantee that a single MyLogger object works properly for a multithreaded system.
How must this code be changed to be thread-safe?

Given:
1. public class MyLogger {
2. private StringBuilder logger = new StringBuuilder();
3. public void log(String message, String user) {
4. logger.append(message);
5. logger.append(user);
6. }
7. }
The programmer must guarantee that a single MyLogger object works properly for a multithreaded system.
How must this code be changed to be thread-safe?

A.
replace StringBuilder with StringBuffer

B.
No change is necessary, the current MyLogger code is already thread-safe.

C.
replace StringBuilder with just a String object and use the string concatenation (+=) within the
log method

D.
synchronize the log method



Leave a Reply 0

Your email address will not be published. Required fields are marked *