I am trying to make an ExecutorService
implementation that can be provided with a timeout or interrupt for each thread.
In my below example, suppose I am spawning 2 threads
(in actual scenario, this number will be high), then I need to make sure each thread
should be running for 10 minutes
.
That means, Thread1 will run for 10 minutes
and Thread2 will run for 10 minutes as well
. If 10 minutes is over then I need to interrup the thread or timeout.
Below is the code I have so far and I am not able to understand how should I add this interrupt or timeout
functionality here in such a clean way so that if I am making this no of threads
parameter configurable in my code then it should work properly there as well.
public static void main(String[] args) {
final int noOfThreads = 2;
final long exp_time_millis = 600000; //10 minutes
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
for (int i = 0, i< noOfThreads; i++) {
service.submit(new ThreadTask());
}
}
class ThreadTask implements Runnable {
@Override
public void run() {
while(true) {
System.out.println("Thread running...");
try {
/* make a select sql to the database
* and measure how much time it is taking in
* returning the response
*/
} catch (InterruptedException e) {
}
}
}
}
Any suggestions will be of great help.
I have already seen few articles on the SO but I was not able to find anything which matches my scenario and I can implement that easily.
Updated Code:-
I am trying the below code but it gives me error on the catch block in the run method. Not sure if I am doing anything wrong. Can anyone help me?
public class ThreadTimeout {
public static void main(String[] args) {
final int noOfThreads = 2;
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
ScheduledExecutorService scheduleService = Executors.newScheduledThreadPool(noOfThreads);
for (int i = 0; i< noOfThreads; i++) {
final Future future = service.submit(new ThreadTask());
scheduleService.schedule(new Runnable(){
public void run(){
future.cancel(true);
}
}, 10, TimeUnit.MINUTES);
}
}
}
class ThreadTask implements Runnable {
@Override
public void run() {
//make a database connection
while (true) {
System.out.println("Thread running...");
try {
/*
* make a select sql to the database and measure
* how much time it is taking in returning the
* response
*/
} catch (InterruptedException e) {
}
}
}
}