Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

...

Code Block
bgColor#FFCCCC
public enum Day {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public final class Diary {
  private static final ThreadLocal<Day> days = 
    new ThreadLocal<Day>() {
      // Initialize to Monday 
      protected Day initialValue() {
        return Day.MONDAY;
      }
    };

  private static Day currentDay() {
    return days.get();
  }

  public static void setDay(Day newDay) {
    days.set(newDay);
  }
    
  // Performs some thread-specific task
  public void threadSpecificTask() {
    // Do task ...
  }
}

public final class DiaryPool {
  final int NoOfThreads = 2; // Maximum number of threads allowed in pool
  final Executor exec;
  final Diary diary;

  DiaryPool() {
    exec = (Executor) Executors.newFixedThreadPool(NoOfThreads);
    diary = new Diary();
  }

  public void doSomething1() {
    exec.execute(new Runnable() {
      @Override public void run() {
        Diary.setDay(Day.FRIDAY);
        diary.threadSpecificTask();
      }
    });
  } 

  public void doSomething2() {
    exec.execute(new Runnable() {
      @Override public void run() {
        diary.threadSpecificTask();
      }
    });
  }

  public static void main(String[] args) {
    DiaryPool dp = new DiaryPool();
    dp.doSomething1(); // Thread 1, requires current day as Friday
    dp.doSomething2(); // Thread 2, requires current day as Monday
    dp.doSomething2(); // Thread 3, requires current day as Monday
  } 
}

The DiaryPool class uses a thread pool to execute multiple threads. This allows threads to be reused when the pool becomes full. When this happens, the thread-local state of a previous thread may be inherited by a new thread that has just begun execution.

The following table shows a possible execution order:

Time

Thread#Task

Pool Thread

Submitted By Method

Day

1

t1

1

doSomething1()

Friday

2

t2

2

doSomething2()

Monday

3

t3

1

doSomething2()

Friday

In this execution order, the two threads tasks (t1 and t1) started using doSomething2() are expected to see the current day as Monday, however, one of them (t3) inherits the day Friday from the first thread (t1), when that thread is reused.

...

Although this produces the required results for this example, it is not a scalable solution because changing the thread pool size on demand is infeasibleis inadequate when more tasks can be submitted to the pool.

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() {
      @Override 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()}} unless the thread explicitly sets the value before this happens \[[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)

The In this compliant solution, the class Diary does not use a ThreadLocal object in this compliant solution. Also, the class DiaryPool uses local instances of class Diary within the methods doSomething1() and doSomething2(). The Day is uniquely maintained by each instance of the Diary class.

Code Block
bgColor#ccccff
public final class Diary {
  private volatile Day day;

  Diary() {
    day = Day.MONDAY; // Default	
  }

  private Day currentDay() {
    return day;
  }

  public void setDay(Day d) {
    day = d;
  }

  // Performs some thread-specific task
  public void threadSpecificTask() {
    // Do task ...
  }
}

public final class DiaryPool {
  private final int NoOfThreads = 2; // Maximum number of threads allowed in pool
  private final Executor exec;

  DiaryPool() {
    exec = (Executor) Executors.newFixedThreadPool(NoOfThreads);
  }

  public void doSomething1() {
    final Diary diary = new Diary(); // First instance
    exec.execute(new Runnable() {
      @Override public void run() {
        diary.setDay(Day.FRIDAY);
        diary.threadSpecificTask();
      }
    });
  } 

  public void doSomething2() {
    final Diary diary = new Diary(); // Second instance
    exec.execute(new Runnable() {
      @Override public void run() {
        diary.threadSpecificTask();
      }
    });
  }

  public static void main(String[] args) {
    DiaryPool dp = new DiaryPool();
    dp.doSomething1(); // Thread 1, requires current day as Friday
    dp.doSomething2(); // Thread 2, requires current day as Monday 
    dp.doSomething2(); // Thread 2, requires current day as Monday
  } 
}

...

The following table shows a possible execution order that conforms to the requirements:

Time

Thread#Task

Pool Thread

Submitted By Method

Day

1

t1

1

doSomething1()

Friday

2

t2

2

doSomething2()

Monday

3

t3

1 or 2

doSomething2()

Monday

...