blob: 8c03af6e319e34f9bcc7cc74df2177bd8862a0d9 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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<Type> {
val Function0<Type> function;
new(Function0<Type> function) {
this.function = function
}
def execute(long millisecs) {
if(millisecs>0) {
val executor = Executors.newCachedThreadPool();
val task = new Callable<Type>() {
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
}
}
|