Absent Member.
Absent Member.

Fortify Code scan - Use of ThreadLocal

Hi everyone,

     I've a question regarding one of the issue raised in Fortify java code scan. I'm seeing that the use of ThreadLocal is being raised as issue under "J2EE bad Practice: Thread Management ". I'm kind of surprised as why it's being considered bad. Could someone help here with relevant information ?

Here is a sample -


    private static ThreadLocal<HashMap<String, Constructor>> constructLocal = new ThreadLocal<HashMap<String, Constructor>>(){

          @Override protected HashMap<String, Constructor> initialValue() {

            return new HashMap<String, Constructor>();



Thanks in advance.

1 Reply
Cadet 2nd Class Cadet 2nd Class
Cadet 2nd Class

ThreadLocals are additional attributes added to a thread. Threads are usually pooled in J(2)EE, i.e. they are created once and returned into a thread pool. Such ThreadLocals behave like global variables bound to a thread. If the thread isn't used anymore, the thread is “released”, i.e. returned into the pool. The application server doesn't care about the ThreadLocals, it doesn't touch them and also doesn't clean them or release their memory.

If you store sensitive information in ThreadLocals, i.e. information which must not be shared between users or threads, you have to take care of cleaning them up yourself before the thread is released.

If you store data in ThreadLocals, their memory is not released as well. You may run in a memory leak.

See e.g. ThreadLocal and Thread Pools - The Kitchen in the Zoo

The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.