Versions Compared

Key

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

...

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.

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.

...