Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Cached thread pool and thread local

I have a question about java and concurrency.

Let say I have a ThreadLocal variable called 'a'. And I use a CachedThreadPool to obtain new threads. When a thread is reused, what happens to the ThreadLocal variable 'a'? It maintains the same value (cause it is the same thread) or it starts empty (as if the thread was new)?

like image 524
Mateu Avatar asked Sep 13 '11 14:09

Mateu


People also ask

What is cached thread pool Java?

A cached thread pool is useful when tasks submitted for processing should not wait and needs to be addressed as soon as submitted. To satisfy this requirement, Java creates a new thread for the submitted task if there are no thread in the pool to address the task. A cached thread pool can have up to 2³¹ no of threads.

What is difference between fixed thread pool and Cachedthreadpool?

As opposed to the cached thread pool, this one is using an unbounded queue with a fixed number of never-expiring threads. Therefore, instead of an ever-increasing number of threads, the fixed thread pool tries to execute incoming tasks with a fixed amount of threads.

How many types of thread pool are there in Java?

We can create the following 5 types of thread pool executors with pre-built methods in java. util. concurrent.

Should you use a thread pool or just create a new thread whenever you need it?

I would advise you to use a ThreadPool instead of creating a new Thread. You can have a beginning of answer in Oracle's documentation about thread pools.


1 Answers

By default ThreadLocals are reused along with the thread. If you need them to be be reinitialized you can do so by overriding the methods noted below:

from javadoc for java.util.concurrent.ThreadPoolExecutor

Hook methods This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

like image 96
jcwayne Avatar answered Nov 15 '22 05:11

jcwayne