package hu.bme.mit.inf.dlsreasoner.alloy.reasoner.builder import org.eclipse.xtext.xbase.lib.Functions.Function0 import java.util.concurrent.Executors import java.util.concurrent.Callable import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.ExecutionException class FunctionWithTimeout { val Function0 function; new(Function0 function) { this.function = function } def execute(long millisecs) { if(millisecs>0) { val executor = Executors.newCachedThreadPool(); val task = new Callable() { override Type call() { function.apply } }; val future = executor.submit(task); try { val result = future.get(millisecs, TimeUnit.MILLISECONDS); return result } catch (TimeoutException ex) { // handle the timeout } catch (InterruptedException e) { // handle the interrupts } catch (ExecutionException e) { // handle other exceptions } finally { future.cancel(true); // may or may not desire this } return null } else return function.apply } }