Reputation: 1007
Problem: I wanted to know when a RunTimeException is thrown in run method of thread, will thread local of that thread be preserved? Answer to this question lies in what I'm asking below. So with that said, if thread dies(when exception is thrown) it's thread local snapshot get's cleared up or if thread does not die what happens to thread local in that case. Do we need to programmatically handle that? Scenario: During heavy load, request came in and processing took way too long and before response was created, async context times out. What happens in this scenario? What happens to the thread that is processing the request?
Here's more details : I've been researching on how ThreadPoolExecutors internally work. What I'm curious to know is what happens when a RunTimeException is thrown in run method of thread. Does it get killed and ThreadPoolExecutor ends up creating brand new thread? Or JVM somehow does not let that thread to die, so that it can reused in the pool. I think the thread dies and so does it's ThreadLocal snapshot. I wanted to get some insight on exactly how ThreadPoolExecutor handle exceptions and how life cycle of a particular thread revolves around that. Thanks for your help!
Upvotes: 1
Views: 1763
Reputation: 1007
Thanks everyone! I got my answer.
Thread dies when an exception is thrown. Only catch here is if we reference a thread id in thread local that can cause a thread leak if that is not cleared properly.
Thread id can be reused as per java docs. In my case I was putting putting some stuff in thread local referencing to thread id (Thread.currentThread.getId). Best way to clear that up is to override afterExecute(java.lang.Runnable, java.lang.Throwable) and clean up things in there.
From java docs:
public long getId()
Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
Upvotes: 2