wtorek, 17 marca 2015

How to invoke java method with a time limit?

Java has no handy way to do so. You can always use Thread to run a method and after some time out interrupt it.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {

 public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

  ExecutorService executor = Executors.newSingleThreadExecutor();
  Future future = executor.submit(new Runnable() {
   @Override
   public void run() {
    try {
     TimeUnit.DAYS.sleep(1);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  });

  try {
   future.get(5, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
   future.cancel(true);
   throw e;
  } catch (TimeoutException e) {
   future.cancel(true);
   throw e;
  }
 }

}

Brak komentarzy:

Prześlij komentarz