is that even possible?
i have an interface method boolean right(), if it isnt "answering" in a second, it should return false.
is that even possible?
i have an interface method boolean right(), if it isnt "answering" in a second, it should return false.
Well, you can't put that requirement in the interface itself, but if you're controlling the calling side it's possible:
Yes, this is possible with e.g. java.util.concurrent.Future<V>
(the standard interface
to represents the result of an asynchronous computation of type V
), combined with the method get(long timeout, TimeUnit unit)
. The method may throw TimeoutException
, among other exceptions, but otherwise returns the computed result on normal execution.
In this case you want a Future<Boolean>
, with get(1, TimeUnit.SECONDS)
within a try-catch
block, handling TimeOutException
per your specification.
Available concrete implementations are FutureTask<V>
and SwingWorker<T,V>
. If this is within the context of Swing application, then you'd want to use the latter.
Ofcourse it is not possible to add this as a static check (at compile time, something that the compiler can check to ensure it), because how long it takes to run an operation heavily depends on the runtime environment that the program is running in.
You can use the classes in java.util.concurrent
to run an operation and wait for it to finish within a certain timeout. A simple example (not thoroughly tested, but demonstrates the idea):
ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Integer> future = exec.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(10000);
return 123;
}
});
try {
// Run the callable, wait for max. 5 seconds
System.out.println(future.get(5, TimeUnit.SECONDS));
}
catch (TimeoutException ex) {
System.out.println("The operation took too long!");
}