Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: Proposed new Java feature Date: Mon, 28 May 2012 12:13:02 +0200 Lines: 50 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net N8VgwlkoXd+iO52qkwoqfANnikDWaWfjQ61kMbOWImUhJrwgxuoXWZG0pJFJdzRig= Cancel-Lock: sha1:bzoEcmPYbfq9RLPY2FZIXPTcfaU= User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20120430 Thunderbird/12.0.1 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:14857 On 05/27/2012 08:14 PM, Mike Schilling wrote: > "Robert Klemme" wrote in message > news:a2ehm0Fee8U1@mid.individual.net... >>> 2. ThreadLocals interact badly with ThreadPools, because the ThreadLocals >>> keep their value when the tyhread is put back into the pool. This can >>> lead >>> to leaks and even potential security issues. >> >> I would actually consider this good interaction with thread pools: the >> local stays around for as long as the thread lives. If you introduce >> security issues this way than you are probably not using thread locals >> properly. There are two things that you generally need to consider with >> thread locals which both result from the fact that the life time of a >> thread local value extends across a current method call (i.e. earlier and >> later): > > > OK. Now, coinsider these two cases (for, say, a webserver): > > 1. I create a new thread to handle each new request. > 2. I optimize (1) by using a thread pool to minimize thread creation. > > I want those two to behave identically (other than performance). To acheive > that, I need to be able to kill all the ThreadLocals when putting the > Threads back into the pool for later reuse. Otherwise No, you don't. If you employ proper cache size management schemes (e.g. via a LRU) then you do not get rid of the ThreadLocal after each request. If for any reason this is not possible and you want to get rid of state after the request then it should be done per individual ThreadLocal and not globally for all ThreadLocals. > A. The ThreadLocals for threads in the pool cause packratting. Then you do not employ proper cache size management. You always need to be aware of the life time difference between a method call and a ThreadLocal and code appropriately. Not doing this is not following the contract of ThreadLocal. > B. A reused thread contains context created during its previous use. This > may be context that the user correspnding to the request currently being > handled by the thread should not be able to see. Then you are not using ThreadLocal properly, i.e. have omitted proper cleanup (e.g. because you either did not do it or did not do it in a safe way, i.e. finally block). Kind regards robert