Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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() {
      public void run() {
        Diary.setDay(Day.FRIDAY);
        diary.threadSpecificTask();
      }
    });
  } 

  public void doSomething2() {
    exec.execute(new Runnable() {
      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 orderingorder:

Time/Thread#

Pool Thread

Submitted By Method

Day

1

1

doSomething1()

Friday

2

2

doSomething2()

Monday

3

1 or 2

doSomething2()

Friday

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. In this case, even though the threads that were In this execution order, the two threads (2 and 3) started using doSomething2() are expected to see the current day as Monday, however, one of them (thread 3) inherits the day Friday from the first thread (thread 1), when that thread is reused.

...

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

Time/Thread#

Pool Thread

Submitted By Method

Day

1

1

doSomething1()

Friday

2

2

doSomething2()

Monday

3

1 or 2

doSomething2()

Monday

...