Internet is filled with articles on disadvantages of ThreadLocal in Java, and yet people keep using it in Web Development. What I did not find is, is there any alternative to threadlocals in web application?
Asked
Active
Viewed 3,579 times
2
-
2Yes and no. Your question is too broad. Alternatives depend on your usecase. Could you add more details, e.g. what are you doing and why ThreadLocal is not good for you? – AlexR Jun 20 '18 at 12:15
-
I'm using it for the same reason every web application uses it, to store thread specific variables, and the reason i think its not good is, if some developer somehow forgets to reset the value, the next thread might use the previous value, and there is always the memory leak that is associated with threadlocals – prem Jun 20 '18 at 12:20
-
Can you give code examples? Also, there should not be memory leaks if you know what you are doing. ThreadLocalMap uses WeakReferences, so if you don't have a reference to threadLocal variable and you don't have a circular dependency from value to the threadLocal then you will not have a memory leak. – CodesInTheDark Jul 18 '19 at 10:00
-
In spring framework, there is an alternative approach to achieve it. Refer this links https://stackoverflow.com/questions/25406157/spring-request-scope-vs-java-thread-local https://dzone.com/articles/an-alternative-approach-to-threadlocal-using-sprin-1 – Hari Bharathi Sep 25 '20 at 13:29
-
Nothing wrong with `ThreadLocal` *per se,* but people use it inappropriately. In Web applications you should be using the request or session scope. – user207421 Jul 11 '23 at 23:56
2 Answers
1
JDK 20 includes an alternative to ThreadLocals called Scoped Values. This gives a way to specify storing values in a specified scope so that other code in the same thread (or in other threads that call it) can access them. Unlike ThreadLocal the scoped value is immutable once set so downstream code can't tamper with it.

Nathan Hughes
- 94,330
- 19
- 181
- 276
0
There is an alternative to hide direct ThreadLocal usage using Spring.
See https://tech.asimio.net/2017/11/28/An-alternative-to-ThreadLocal-using-Spring.html.
It still uses it but minimizes its usage to reduce the possibility of errors, such as not cleaning it after processing web requests

ootero
- 3,235
- 2
- 16
- 22