Is there a standard nice way to call a blocking method with a timeout in Java? I want to be able to do:
// call something.blockingMethod(); // if it hasn't come back within 2 seconds, forget it
if that makes sense.
Thanks.
The java. lang. Object. wait(long timeout) causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.
Exit a Java Method using Returnexit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function.
You could use an Executor:
ExecutorService executor = Executors.newCachedThreadPool(); Callable<Object> task = new Callable<Object>() { public Object call() { return something.blockingMethod(); } }; Future<Object> future = executor.submit(task); try { Object result = future.get(5, TimeUnit.SECONDS); } 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 }
If the future.get
doesn't return in 5 seconds, it throws a TimeoutException
. The timeout can be configured in seconds, minutes, milliseconds or any unit available as a constant in TimeUnit
.
See the JavaDoc for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With