phuongdo
phuongdo

Reputation: 271

Putting a time out on individual threads inside ThreadPoolExecutor

I am using the threadPoolExecutor class from the java api to handle all my threads. At the moment i have 5 threads that can exist in the thread pool. My threads are all doing the same task. They are doing a requests to the database and they wait for a reply. Some times the database does not reply for some time. This means these threads get stuck in the thread pool waiting.

I was wondering was there any way to set a time out on threads in the thread pool. so if a thread is running for more than half an hour then the thread pool will kill it and process the next thread in the queue. I do not

At the moment the threads inside the thread pool have their own timer task that writes to a log saying the thread is taking more than 30 minutes. I am trying to think of a way of killing off threads that take this long.

How can I do that !

Upvotes: 0

Views: 1872

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

Keep-alive times

If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see getKeepAliveTime(java.util.concurrent.TimeUnit)). This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method setKeepAliveTime(long, java.util.concurrent.TimeUnit). Using a value of Long.MAX_VALUE TimeUnit.NANOSECONDS effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSizeThreads. But method allowCoreThreadTimeOut(boolean) can be used to apply this time-out policy to core threads as well, so long as the keepAliveTime value is non-zero.

From the ThreadPoolExecutor Java docs

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. Use CachedThreadPool.

2. CachedThreadPool will pool, will be starting of with defined number of threads. Now depending of the necessity it can span new thread.

3. Most amazing and your desired feature of CachedThreadPool is that, when a thread is not involved in any activity for 60 seconds, then it is killed.

Upvotes: 0

Related Questions