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.
First, if you are using java.sql.Statement or java.sql.PreparedStatement, the first thing I would do is try the setQueryTimeout(inSeconds) method. If you are not using the built in JDBC API I would check the API you are using to see if it has a similar approach.
Otherwise I would check if there is a way to interrupt the database request (such as interrupting the Thread, or forcing some other exception to occur). My strategy would be to take that TimerTask you have and instead of logging, use it to force the other thread to end. I am not sure the best route to do this - it probably depends on what is happening. But my first try would be to do Thread.interrupt(), and if that doesn't work I would look to forcing some other exception (maybe a SQLException). Not all blocking tasks can be interrupted, and maybe you can't force some other exception to occur either.
Thanks for getting back to me. The database does not provide a way to set a time out. It is a proprietary database that is not that good. I had look at the API and does not give a time out for queries which is kind of stupid.
I will probably have to throw an exception from the timer thread and do a interrupt.