I have a task executor which takes runnable
as a task. I am starting a timer before calling runnable.run()
method and stopping it when the runnable finished. I want to terminate the execution of run()
method from the executor itself if the timer exceeds the time limit. I do not know what user will implement in run()
.
TaskExecutor.add(new Runnable () {
@Override
public void run() {
System.out.println("This is test job");
}}
);
This is how the user adds a new task. Every task runs in the same thread.
Edit
This task executor will act as a service
to users. And because creating threads are expensive operation and requires native
OS calls, I am trying to avoid them. Otherwise I would call Thread.interrupt()
at some point. But I just want to know if there is a way to terminate the run()
method from a parent object. Terminate means to stop something abruptly. As how we terminate processes in OS task manager.
How tasks are executed
while (jobQueue.isEmpty()) {
for (Job job : jobQueue) {
long startTime = System.currentTimeMillis();
job.run();
//There is a separate thread which checks
//for timeout flags by comparing the startTime
//with the current time. But all tasks are
//executed in the same thread sequentially. I
//only want to terminate single jobs that are
//timed out.
}
}