Versions Compared

Key

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

...

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 RemovedImage Added


Exceptions

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

...