Versions Compared

Key

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

...

Wiki Markup
The use of {{ThreadLocal}} objects is insecure in classes whose objects are required to be executed by multiple threads in a thread pool. The technique of thread pooling allows threads to be reused when thread creation overhead is too highexpensive or creating an unbounded number of threads can affect the reliability of the system. Every thread that enters the pool expects to see an object in its initial, default state. However, when {{ThreadLocal}} objects are modified from a thread which is subsequently made available for reuse, the reused thread sees the state of the {{ThreadLocal}} object as set by the previous thread instead of the expected default state \[[JPL 06|AA. Java References#JPL 06]\].

...

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 creates a thread pool to execute multiple threads. This allows threads to be reused when the pool becomes full. When this happensthat reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most NoOfThreadsthreads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. When a thread is recycled in this manner, the thread-local state of a previous thread may be inherited by a new thread that has just begun executionthe thread persists.

The following table shows a possible execution order:

Time

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, it is expected that the two tasks (t1 and t1) started using doSomething2() are expected to see will observe the current day as Monday, however, one of them because pool thread 1 is reused (t3) inherits observes the day Friday from the first thread, when that thread is reusedto be Friday .

Noncompliant Code Example (Increase Thread Pool Size)

This noncompliant code example increases the size of the thread pool from 2 two to 3 three to mitigate the issue.

Code Block
bgColor#FFCCCC
public final class DiaryPool {
  final int NoOfThreads = 3;
  // ...
}

Although this produces the required results for this example, it is not a scalable solution because changing the thread pool size is 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.

...

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 refactoredmodified.

Compliant Solution (

...

Instance Per Call)

In this compliant solution, the class Diary does not use a ThreadLocal object. 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.

...

Time

Task

Pool Thread

Submitted By Method

Day

1

t1

1

doSomething1()

Friday

2

t2

2

doSomething2()

Monday

3

t3

1 or 2

doSomething2()

Monday

Exceptions

CON27-EX1: Sometimes If the state of the ThreadLocal object does not change beyond its initial valueafter initialization, it is safe to use a thread pool. For example, there may be only one type of database connection represented by the initial value of the ThreadLocal object. In the absence of mutability, it is safe to use a thread pool.

Risk Assessment

When objects of classes that use ThreadLocal data are executed in a thread pool by different threads, the objects might acquire stale values, resulting in corrupt state.

...