The task is to read from InputStream and wait for the result up to a configurable amount of time.
Given two options, which one is preferable? Or suggest another one.
- blocking call to read() method which you have to timeout yourself
non-blocking call to available(), which you have to poll using busy waiting with sleep
import java.io.IOException; import java.io.InputStream; import java.util.concurrent.*; public class MyClass { public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { MyClass myClass = new MyClass(); final InputStream in = System.in; final long timeout = 1000; final int result = myClass.blockingWithTimeout(in, timeout); // final int result = myClass.nonBlockingBusyWait(in, timeout); System.out.println("Result " + result); } public int nonBlockingBusyWait(final InputStream is, long timeoutMs) throws IOException, InterruptedException { final long start = System.currentTimeMillis(); while (is.available() == 0 && (System.currentTimeMillis() < start + timeoutMs)) { Thread.sleep(1); } if (is.available() == 0) { return -1; } else { return is.read(); } } public int blockingWithTimeout(final InputStream is, long timeoutMs) throws InterruptedException, ExecutionException { ExecutorService es = Executors.newSingleThreadExecutor(); Future<Integer> future = es.submit((Callable<Integer>) is::read); try { return future.get(timeoutMs, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { return -1; } catch (InterruptedException | ExecutionException e) { throw e; } finally { future.cancel(true); } } }
available()
. It's behavior unspecified by the standard in case of EOFcurrentTimeMillis()
. Always subtract the deadline and compare with zero.