Is it really my job to clean up ThreadLocal resources when classes have been exposed to a thread pool?

前端 未结 5 1287
臣服心动
臣服心动 2021-01-31 14:21

My use of ThreadLocal

In my Java classes, I sometimes make use of a ThreadLocal mainly as a means of avoiding unnecessary object creation:



        
5条回答
  •  感情败类
    2021-01-31 14:55

    Since the thread was not created by you, it only was rented by you, I think it is fair to require to clean it before stop using - just as you fills up the tank of a rented car when returning. Tomcat could just clean everything itself, but it does you a favor, reminding of forgot things.

    ADD: The way you use prepared GregorianCalendar is simply wrong: since service requests can be concurrent, and there is no synchronization, doCalc can take getTime ater setTime invoked by another request. Introducing synchronization would make things slow, so that creating a new GregorianCalendar could be a better option.

    In other words, your question should be: how to keep pool of prepared GregorianCalendar instances so that its number is adjusted to request rate. So as a minimum, you need a singleton which contains that pool. Each Ioc container has means to manage a singleton, and most have ready object pool implementations. If you do not yet use an IoC container, start to use one (String, Guice), rather than reinvent the wheel.

提交回复
热议问题