Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: cleaner code for CS

...

Compliant Solution (try-finally clause)

This compliant solution adds the removeDay() method to the Diary class and wraps the statements in the doSomething1() method of class DiaryPool in a try-finally block. The finally block restores the initial state of the thread local object days by removing the current thread's value from it.

Code Block
bgColor#ccccff

public final class Diary {
  // ...
  public static void removeDay() {
    days.remove();
  }
}

public final class DiaryPool {
  // ...

  public void doSomething1() {
    exec.execute(new Runnable() {
      public void run() {
    	try {  
          Diary.setDay(Day.FRIDAY);
          diary.threadSpecificTask();
    	} finally {
    	  Diary.removeDay(); // Diary.setDay(Day.MONDAY); can also be used	
    	}
      }
    });
  }
 
  // ...
}

Wiki Markup
If the thread local variable is read by the same thread again, it is reinitialized using {{initialValue()}} \[[API 06|AA. Java References#API 06]\]. This solution transfers the burden of maintainability to the client ({{DiaryPool}}) but is a good option when the {{Diary}} class cannot be refactored.

Compliant Solution (instance per call)

...