Question 90
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 multi-threaded system. How must this code be changed
to be thread-safe?
A. synchronize the log method
B. replace StringBuilder with StringBuffer
C. No change is necessary, the current MyLogger code is already
thread-safe.
D. replace StringBuilder with just a String object and use the string
concatenation (+=) within the log method
Answer: A大家帮帮忙解释一下

解决方案 »

  1.   

    A. synchronize the log method
    B. replace StringBuilder with StringBuffer
    C. No change is necessary, the current MyLogger code is already
    thread-safe.
    D. replace StringBuilder with just a String object and use the string
    concatenation (+=) within the log method
    Answer: A大家帮帮忙解释一下A. synchronize the log method 意思就是public void log(String message, String user) 
    --》public synchronize  void log(String message, String user) 
    我感觉也是A
      

  2.   

    因为加了synchronize后,就等于在对象上加了锁,锁的粒度是整个对象。所以在多线程环境中只可能一个线程获得此对象锁,也就说只能一个接一个的线程来访问此对象,因此答案为A 别的三个都非线程安全
      

  3.   

    虽然StringBuffer是thread-safe的,但是用于本题却不代表执行结果是thread-safe.从本题的意思来看,原子操作为:
    4. logger.append(message);
    5. logger.append(user); 
    4,5步依次一次性执行或要嘛都不执行。在multi-thread,如果多个线程都申请调用public void log(String message, String user)方法,在该方法没有加synchronized标识符的情况下,可能会出现message和user不是成对依次加入的情况。可能会出现
    mes mes user user这样的的错误的结构。所以选择A,对logger的操作是线程安全的。选B无法保证。