Versions Compared

Key

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

...

public void foo() {
    final int x = dataSource.getCount();
    // do things with x
    // ...
}

ThreadLocal

Be careful when using ThreadLocal (or InheritableThreadLocal). Without careful consideration, ThreadLocal ThreadLocal is a nice Java construct that allows you to isolate state across different threads (https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html). However, uncareful usage of ThreadLocal (or InheritableThreadLocal) can easily lead to memory leaks. As a rule of thumb, they are safe to use if the thread executing the code is short lived. Otherwise, care must be made to remove the ThreadLocal once it is no longer needed.

...

The longer explanation is that each thread contains a Map of all the ThreadLocal objects created by any code executed by that Thread. For example:

Image RemovedImage Added

These objects are garbage collected if the thread goes away. However, if thread is long running (for example, it is used in a thread pool), these objects will never get garbage collected. In the example above, every time an instance of ExampleClass is created, a new entry will be added to the ThreadLocalMap inside the current Thread. If the thread never exits, memory will leak until the process dies. See

Jira Legacy
serverCask Community Issue Tracker
serverId45b48dee-c8d6-34f0-9990-e6367dc2fe4b
keyCDAP-14998
 for an example of this in the past.

...

If you are not absolutely certain that the Thread using the ThreadLocal is short-lived, you must be sure to remove the ThreadLocal once it is no longer needed. Much like closing an InputStream in a finally block, classes that use a ThreadLocal must have a way to release all their resources. In the example below, a close() method is added to the ExampleClass that removes the ThreadLocal. After this, we can see that the Map in the ThreadLocal no longer has the objects.Image Removed

Image Added

Another option if possible is to make the ThreadLocal static so that there is only instance per thread.

Exceptions

This section gives general guidance on the use of exceptions when programming in Java.

...