users@glassfish.java.net

Re: ThreadLocals in request threads

From: Oleksiy Stashok <oleksiy.stashok_at_oracle.com>
Date: Mon, 24 Mar 2014 19:31:12 -0700

Hi Premraj,


On 21.03.14 07:04, Motling, Premraj wrote:
>
> What happens when there is an exception in request thread? Does it go
> to pool or just die?
>
goes to pool

> Background -
>
> I'm using ThreadLocal in my application and at one point (say A) I
> populate some values and at another point (say B) use those values for
> some decision making and then clear those values. I'm more interested
> in what will happen if something happens (say exception or anything)
> and I couldn't clear those values from ThreadLocal. Since same thread
> may go pool again causing issues in future?
>
Yes

> But this seems like very basic problem to me and then ThreadLocals
> cannot be used at all -- so just wanted to confirm whether I'm missing
> anything here?
>
That's also correct :) IMHO it's better to avoid building up application
logic based on ThreadLocals, because then, if you decide to use some
asynchronous API (async Servlets, EJB ... etc) - you'll have to redesign
your code and rid of ThreadLocals.

Particularly in your case, when you're sure everything is running in a
single thread - it would be a good idea to put the ThreadLocal-based
logic into try-finally block and do the ThreadLocals cleanup in "finally".

Thanks.

WBR,
Alexey.