Can anyone guide me on how I can use a simple timeout in java? Basically in my project I'm executing a statement br.readLine()
, which is reading a response from a modem. But sometimes the modem isn't responding. For that purpose I want to add a timeout.
I'm looking for a code like:
try {
String s= br.readLine();
} catch(TimeoutException e) {
System.out.println("Time out has occurred");
}
What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is
final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
try {
handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
handler.cancel(true);
}
executor.shutdownNow();
final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
executor.schedule(new Runnable() {
@Override
public void run(){
handler.cancel(true);
}
}, timeout.toMillis(), TimeUnit.MILLISECONDS);
executor.shutdownNow();
Those are only a draft so that you can get the main idea.