@Test public void wrappedSourceTimesOut() throws Exception { Source source = new ForwardingSource(new Buffer()) { @Override public long read(Buffer sink, long byteCount) throws IOException { try { Thread.sleep(500); return -1; } catch (InterruptedException e) { throw new AssertionError(); } } }; AsyncTimeout timeout = new AsyncTimeout(); timeout.timeout(250, TimeUnit.MILLISECONDS); Source timeoutSource = timeout.source(source); try { timeoutSource.read(new Buffer(), 0); fail(); } catch (InterruptedIOException expected) { } }
@Test public void wrappedSourceCloseTimesOut() throws Exception { Source source = new ForwardingSource(new Buffer()) { @Override public void close() throws IOException { try { Thread.sleep(500); } catch (InterruptedException e) { throw new AssertionError(); } } }; AsyncTimeout timeout = new AsyncTimeout(); timeout.timeout(250, TimeUnit.MILLISECONDS); Source timeoutSource = timeout.source(source); try { timeoutSource.close(); fail(); } catch (InterruptedIOException expected) { } }
/** * Returns a source that reads from {@code socket}. Prefer this over {@link * #source(InputStream)} because this method honors timeouts. When the socket * read times out, the socket is asynchronously closed by a watchdog thread. */ public static Source source(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Source source = source(socket.getInputStream(), timeout); return timeout.source(source); }