Thursday, June 23, 2016

Asynchronous thread with timeout

Recently I have problem to start asynchronous process with timeout. More precisely I want main process to start new thread with some computation task. If task execution exceed some given time period than task is killed. I know how to do that in old 1.4 Java with thread instance for task in some thread group and some watchdog thread.

After some time I wrote following code:

@Test
public void scheduler() throws Exception {
 final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

 FutureTask task = new FutureTask(() -> {
  try {
   System.out.println("task started");
   TimeUnit.SECONDS.sleep(10);
   System.out.println("task je dokoncen");
  } catch (InterruptedException e) {
   System.out.println("interrupted");
   return "task is done with interruption";
  }
  return "task is done";
 });

 scheduler.schedule(task, 100, TimeUnit.MILLISECONDS);

 scheduler.schedule(() -> {
  System.out.println("kill job is started");
  task.cancel(true);
  System.out.println("kill job is done");
  return "";
 } , 2, TimeUnit.SECONDS);

 System.out.println("I'm going to wait for ending both tasks");

 TimeUnit.SECONDS.sleep(20);
}

No comments:

Post a Comment