public byte[] read(int readSize) throws IOException { InputStream input = this.input; byte[] data = new byte[readSize]; int remain = readSize; if (input == null) { throw new SocketException("Socket already closed."); } while (remain > 0) { try { int read = input.read(data, readSize - remain, remain); if (read > -1) { remain -= read; } else { throw new IOException("EOF encountered."); } } catch (SocketTimeoutException te) { if (Thread.interrupted()) { throw new ClosedByInterruptException(); } } } return data; }
public byte[] read(int readSize, int timeout) throws IOException { InputStream input = this.input; byte[] data = new byte[readSize]; int remain = readSize; int accTimeout = 0; if (input == null) { throw new SocketException("Socket already closed."); } while (remain > 0 && accTimeout < timeout) { try { int read = input.read(data, readSize - remain, remain); if (read > -1) { remain -= read; } else { throw new IOException("EOF encountered."); } } catch (SocketTimeoutException te) { if (Thread.interrupted()) { throw new ClosedByInterruptException(); } accTimeout += SO_TIMEOUT; } } if (remain > 0 && accTimeout >= timeout) { throw new SocketTimeoutException("Timeout occurred, failed to read total " + readSize + " bytes in " + timeout + " milliseconds, actual read only " + (readSize - remain) + " bytes"); } return data; }
@Override public void read(byte[] data, int off, int len, int timeout) throws IOException { InputStream input = this.input; int accTimeout = 0; if (input == null) { throw new SocketException("Socket already closed."); } int n = 0; while (n < len && accTimeout < timeout) { try { int read = input.read(data, off + n, len - n); if (read > -1) { n += read; } else { throw new IOException("EOF encountered."); } } catch (SocketTimeoutException te) { if (Thread.interrupted()) { throw new ClosedByInterruptException(); } accTimeout += SO_TIMEOUT; } } if (n < len && accTimeout >= timeout) { throw new SocketTimeoutException("Timeout occurred, failed to read total " + len + " bytes in " + timeout + " milliseconds, actual read only " + n + " bytes"); } }
@Override public void write(final int b) throws IOException { oneByteBuffer.flip(); oneByteBuffer.clear(); oneByteBuffer.put((byte) b); oneByteBuffer.flip(); final int timeoutMillis = this.timeout; long maxTime = System.currentTimeMillis() + timeoutMillis; int bytesWritten; long sleepNanos = 1L; while (oneByteBuffer.hasRemaining()) { bytesWritten = channel.write(oneByteBuffer); if (bytesWritten == 0) { if (System.currentTimeMillis() > maxTime) { throw new SocketTimeoutException("Timed out writing to socket"); } try { TimeUnit.NANOSECONDS.sleep(sleepNanos); } catch (InterruptedException e) { close(); Thread.currentThread().interrupt(); // set the interrupt status throw new ClosedByInterruptException(); // simulate an interrupted blocked write operation } sleepNanos = Math.min(sleepNanos * 2, CHANNEL_FULL_WAIT_NANOS); } else { return; } } }
@Override public void write(final byte[] b, final int off, final int len) throws IOException { final ByteBuffer buffer = ByteBuffer.wrap(b, off, len); final int timeoutMillis = this.timeout; long maxTime = System.currentTimeMillis() + timeoutMillis; int bytesWritten; long sleepNanos = 1L; while (buffer.hasRemaining()) { bytesWritten = channel.write(buffer); if (bytesWritten == 0) { if (System.currentTimeMillis() > maxTime) { throw new SocketTimeoutException("Timed out writing to socket"); } try { TimeUnit.NANOSECONDS.sleep(sleepNanos); } catch (InterruptedException e) { close(); Thread.currentThread().interrupt(); // set the interrupt status throw new ClosedByInterruptException(); // simulate an interrupted blocked write operation } sleepNanos = Math.min(sleepNanos * 2, CHANNEL_FULL_WAIT_NANOS); } else { maxTime = System.currentTimeMillis() + timeoutMillis; } } }
private int readData(final ByteBuffer dest) throws IOException { final long startTime = System.currentTimeMillis(); while (true) { if (interrupted) { throw new TransmissionDisabledException(); } if (dest.remaining() == 0) { return 0; } final int readCount = channel.read(dest); long sleepNanos = 1L; if (readCount == 0) { if (System.currentTimeMillis() > startTime + timeoutMillis) { throw new SocketTimeoutException("Timed out reading from socket connected to " + hostname + ":" + port); } try { TimeUnit.NANOSECONDS.sleep(sleepNanos); } catch (InterruptedException e) { close(); Thread.currentThread().interrupt(); // set the interrupt status throw new ClosedByInterruptException(); } sleepNanos = Math.min(sleepNanos * 2, BUFFER_FULL_EMPTY_WAIT_NANOS); continue; } logger.trace("{} Read {} bytes", this, readCount); return readCount; } }
private void writeFully(final ByteBuffer src) throws IOException { long lastByteWrittenTime = System.currentTimeMillis(); int bytesWritten = 0; while (src.hasRemaining()) { if (interrupted) { throw new TransmissionDisabledException(); } final int written = channel.write(src); bytesWritten += written; final long now = System.currentTimeMillis(); long sleepNanos = 1L; if (written > 0) { lastByteWrittenTime = now; } else { if (now > lastByteWrittenTime + timeoutMillis) { throw new SocketTimeoutException("Timed out writing to socket connected to " + hostname + ":" + port); } try { TimeUnit.NANOSECONDS.sleep(sleepNanos); } catch (final InterruptedException e) { close(); Thread.currentThread().interrupt(); // set the interrupt status throw new ClosedByInterruptException(); } sleepNanos = Math.min(sleepNanos * 2, BUFFER_FULL_EMPTY_WAIT_NANOS); } } logger.trace("{} Wrote {} bytes", this, bytesWritten); }
/** * Indicates the end of a code section that has been started with * {@code begin()} and that includes a potentially blocking I/O operation. * * @param success * pass {@code true} if the blocking operation has succeeded and * has had a noticeable effect; {@code false} otherwise. * @throws AsynchronousCloseException * if this channel is closed by another thread while this method * is executing. * @throws ClosedByInterruptException * if another thread interrupts the calling thread while this * method is executing. */ protected final void end(boolean success) throws AsynchronousCloseException { Thread.currentThread().popInterruptAction$(interruptAndCloseRunnable); if (interrupted) { interrupted = false; throw new ClosedByInterruptException(); } if (!success && closed) { throw new AsynchronousCloseException(); } }
private void checkIfClosedOrInterrupted() throws IOException { if ( !isOpen() ) { throw new ClosedChannelException(); } if ( Thread.currentThread().isInterrupted() ) { close(); throw new ClosedByInterruptException(); } }
@Test public void shouldNotReportClosedByInterruptException() throws Exception { when(mockAgent.doWork()).thenThrow(new ClosedByInterruptException()); assertExceptionNotReported(); }
@Test public void shouldNotReportClosedByInterruptException() throws Exception { when(mockAgent.doWork()).thenThrow(new ClosedByInterruptException()); assertExceptionNotReported(); }
@Test public void shouldNotReportRethrownClosedByInterruptException() throws Exception { when(mockAgent.doWork()).thenAnswer( (inv) -> { try { throw new ClosedByInterruptException(); } catch (final ClosedByInterruptException ex) { LangUtil.rethrowUnchecked(ex); } return null; }); assertExceptionNotReported(); }
@Test public void shouldNotReportRethrownClosedByInterruptException() throws Exception { when(mockAgent.doWork()).thenAnswer( (inv) -> { try { throw new ClosedByInterruptException(); } catch (final ClosedByInterruptException ex) { LangUtil.rethrowUnchecked(ex); } return null; }); assertExceptionNotReported(); }
ExceptionHandler handler = ExceptionHandler.newBuilder().retryOn(IOException.class).build(); assertTrue(handler.shouldRetry(new IOException(), null)); assertTrue(handler.shouldRetry(new ClosedByInterruptException(), null)); assertFalse(handler.shouldRetry(new RuntimeException(), null)); assertFalse(handler.shouldRetry(new ClosedByInterruptException(), null)); assertFalse(handler.shouldRetry(new InterruptedException(), null)); assertFalse(handler.shouldRetry(new RuntimeException(), null)); handler = builder.build(); assertFalse(handler.shouldRetry(new IOException(), null)); assertFalse(handler.shouldRetry(new ClosedByInterruptException(), null)); assertFalse(handler.shouldRetry(new InterruptedException(), null)); assertFalse(handler.shouldRetry(new RuntimeException(), null)); assertTrue(handler.shouldRetry(new ClosedByInterruptException(), null)); assertTrue(handler.shouldRetry(new InterruptedException(), null)); assertTrue(handler.shouldRetry(new RuntimeException(), null)); assertTrue(handler.shouldRetry(new ClosedByInterruptException(), null)); assertTrue(handler.shouldRetry(new InterruptedException(), null)); assertTrue(handler.shouldRetry(new RuntimeException(), null));
try { ... } catch (InterruptedException e) { close(); // obeying API of ClosedByInterruptException Thread.currentThread().interrupt(); // again, obeying API throw new ClosedByInterruptException(); }
@Override public void write(byte[] b, int off, int len) throws IOException { if (interrupted) { throw new ClosedByInterruptException(); } writing = true; try { SubstrateServerMessage message = new SubstrateServerMessage(command, b, off, len); SubstrateServerMessage.send(message, original); } finally { writing = false; } }
private void waitForFetchWithRetry() throws IOException { try { RetryHelper.runWithRetries(new Callable<Void>() { @Override public Void call() throws IOException, InterruptedException { waitForFetch(); return null; }}, retryParams, GcsServiceImpl.exceptionHandler); } catch (RetryInterruptedException e) { closed = true; throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }
public void flushWrites(final boolean metadata) throws IOException { assertOpen(); try { m_writeCacheService.flush(metadata); // sync the disk. m_reopener.reopenChannel().force(metadata); final StoreCounters<?> c = (StoreCounters<?>) storeCounters.get() .acquire(); try { c.nforce++; } finally { c.release(); } } catch (InterruptedException e) { throw new ClosedByInterruptException(); } }
public void flushWrites(final boolean metadata) throws IOException { assertOpen(); try { m_writeCacheService.flush(metadata); // sync the disk. m_reopener.reopenChannel().force(metadata); final StoreCounters<?> c = (StoreCounters<?>) storeCounters.get() .acquire(); try { c.nforce++; } finally { c.release(); } } catch (InterruptedException e) { throw new ClosedByInterruptException(); } }
@Override public GcsFileMetadata getMetadata(final GcsFilename filename) throws IOException { try { return RetryHelper.runWithRetries(new Callable<GcsFileMetadata>() { @Override public GcsFileMetadata call() throws IOException { long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt(); return raw.getObjectMetadata(filename, timeout); } }, options.getRetryParams(), exceptionHandler); } catch (RetryInterruptedException ex) { throw new ClosedByInterruptException(); } catch (NonRetriableException e) { Throwables.propagateIfInstanceOf(e.getCause(), IOException.class); throw e; } }