4

I am working on a web service and creating thread local instances and only want to remove them during app shutdown (once a threadlocal object is created for thread I want use that object during different service calls on that thread). As threads are created and owned by tomcat , is there any way to remove those threadlocals during application shutdown ??

user1875798
  • 263
  • 3
  • 6
  • 16
  • Add a shutdown hook a thread and release thread locals, which only run at the time application goes down. `Runtime.getRuntime()#addShutdownHook()` – Subhrajyoti Majumder Mar 07 '14 at 07:48
  • possible duplicate of [shutdown hook for java web application](http://stackoverflow.com/questions/1549924/shutdown-hook-for-java-web-application) – Scary Wombat Mar 07 '14 at 07:49
  • possible duplicate of [How to clean up threadlocals](http://stackoverflow.com/q/3869026/17300) – Stephen P Jun 04 '15 at 19:22

1 Answers1

2

Tomcat 6 has memory leak detection in place, and Tomcat 7 has actual removal logic - it will automatically remove all thread local objects for you: http://wiki.apache.org/tomcat/MemoryLeakProtection

Ideally you should remove all objects from thread local after request is completed, since the same thread is going to be put back to thread pool and used to serve other requests - in this case thread local values may interfere with subsequent request logic, and cause all kind of security issues.

But if you're specifically looking to keep values in thread local for the whole duration of Tomcat webapp lifetime - Tomcat 7 will take care of cleaning it up for you on webapp shutdown, think of it as garbage collection.

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
  • I am using tomcat8 and I still get it – Dejell Jan 22 '15 at 19:12
  • You still get _what_? If you get notification about memory leak detected and stale objects removed, that's expected – Oleg Mikheev Jan 23 '15 at 03:20
  • I get an error about memory leak in tomcat8. I thought that it's taking care of it.Also when I run shutdown.sh it doesn't shut down the tomcat I need to kill the process. is it related? – Dejell Jan 23 '15 at 07:57
  • what is the error? it shouldn't be an error. and if tomcat doesn't stop you probably have something that can't get killed, db connection? – Oleg Mikheev Jan 23 '15 at 08:07
  • I posted a new question here: http://stackoverflow.com/questions/28105803/tomcat8-memory-leak as the error was too long for a comment – Dejell Jan 23 '15 at 08:30