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.

...

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.

...