java.nio.channels.AsynchronousCloseException Java Examples

The following examples show how to use java.nio.channels.AsynchronousCloseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsyncMessageReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Handler for "read failed" event.
 */
public void failed(Throwable exc, Void v) {
    if (getMessageListener(false) != null) {
        // force any error to unblock pending message listener
        synchronized (this.pendingMsgMonitor) {
            this.pendingMsgMonitor.notify();
        }
        if (AsynchronousCloseException.class.equals(exc.getClass())) {
            this.currentMessageListener.closed();
        } else {
            this.currentMessageListener.error(exc);
        }
    }
    // it's "done" after sending a closed() or error() signal
    this.currentMessageListener = null;
}
 
Example #2
Source File: ServerSocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Regression test for HARMONY-6375
 */
public void test_accept_configureBlocking() throws Exception {
    InetSocketAddress localAddr = new InetSocketAddress("localhost", 0);
    serverChannel.socket().bind(localAddr);

    // configure the channel non-blocking
    // when it is accepting in main thread
    new Thread() {
        public void run() {
            try {
                Thread.sleep(TIME_UNIT);
                serverChannel.configureBlocking(false);
                serverChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();

    try {
        serverChannel.accept();
        fail("should throw AsynchronousCloseException");
    } catch (AsynchronousCloseException expected) {
    }
    serverChannel.close();
}
 
Example #3
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
        throws IOException {
    assertTrue(this.channel2.isBlocking());

    new Thread() {
        public void run() {
            try {
                Thread.sleep(TIME_UNIT);
            } catch (InterruptedException ie) {
                fail();
            }
            IoUtils.closeQuietly(channel2);
        }
    }.start();

    try {
        this.channel2.read(targetBuf);
        fail("Should throw AsynchronousCloseException");
    } catch (AsynchronousCloseException e) {
        // OK.
    }
}
 
Example #4
Source File: AsyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void failed(Throwable exc, Void attachment) {
    if (getMessageListener(false) != null) {
        // force any error to unblock pending message listener
        synchronized (AsyncMessageReader.this.pendingMsgMonitor) {
            AsyncMessageReader.this.pendingMsgMonitor.notify();
        }
        if (AsynchronousCloseException.class.equals(exc.getClass())) {
            AsyncMessageReader.this.currentMessageListener.error(new CJCommunicationsException("Socket closed", exc));
        } else {
            AsyncMessageReader.this.currentMessageListener.error(exc);
        }
    }
    // it's "done" after sending a closed() or error() signal
    AsyncMessageReader.this.currentMessageListener = null;
}
 
Example #5
Source File: SocketChannelImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a byte of out of band data.
 */
int sendOutOfBandData(byte b) throws IOException {
    writeLock.lock();
    try {
        boolean blocking = isBlocking();
        int n = 0;
        try {
            beginWrite(blocking);
            if (blocking) {
                do {
                    n = Net.sendOOB(fd, b);
                } while (n == IOStatus.INTERRUPTED && isOpen());
            } else {
                n = Net.sendOOB(fd, b);
            }
        } finally {
            endWrite(blocking, n > 0);
            if (n <= 0 && isOutputClosed)
                throw new AsynchronousCloseException();
        }
        return IOStatus.normalize(n);
    } finally {
        writeLock.unlock();
    }
}
 
Example #6
Source File: AsyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Handler for "read failed" event.
 */
@Override
public void failed(Throwable exc, Void attachment) {
    if (getMessageListener(false) != null) {
        // force any error to unblock pending message listener
        synchronized (AsyncMessageReader.this.pendingMsgMonitor) {
            AsyncMessageReader.this.pendingMsgMonitor.notify();
        }
        if (AsynchronousCloseException.class.equals(exc.getClass())) {
            AsyncMessageReader.this.currentMessageListener.error(new CJCommunicationsException("Socket closed", exc));
        } else {
            AsyncMessageReader.this.currentMessageListener.error(exc);
        }
    }
    // it's "done" after sending a closed() or error() signal
    AsyncMessageReader.this.currentMessageListener = null;
}
 
Example #7
Source File: SimpleSocketServer.java    From antsdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    try {
        for (;;) {
            SocketChannel channel = this.serverChannel.accept();
            channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
            Orca orca = this.fish.getOrca();
            if (orca == null) {
                channel.close();
                continue;
            }
            if (orca.isClosed()) {
                channel.close();
                continue;
            }
            this.pool.execute(new SimpleSocketWorker(this.fish, channel));
        }
    }
    catch (AsynchronousCloseException ignored) {}
    catch (Exception x) {
        _log.warn("", x);
    }
}
 
Example #8
Source File: AbstractInterruptibleChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests AbstractInterruptibleChannel#close/begin/end()
 */
public void test_close_begin_end() throws IOException {
    boolean complete = false;
    MockInterruptibleChannel testChannel = new MockInterruptibleChannel();
    assertTrue(testChannel.isOpen());
    try {
        testChannel.superBegin();
        complete = true;
    } finally {
        testChannel.superEnd(complete);
    }
    assertTrue(testChannel.isOpen());
    testChannel.close();
    try {
        testChannel.superBegin();
        complete = false;
    } finally {
        try {
            testChannel.superEnd(complete);
            fail("should throw AsynchronousCloseException");
        } catch (AsynchronousCloseException e) {
            // expected
        }
    }
    assertFalse(testChannel.isOpen());
    try {
        testChannel.superBegin();
        complete = true;
    } finally {
        testChannel.superEnd(complete);
    }
    assertFalse(testChannel.isOpen());
}
 
Example #9
Source File: NamedPipeSocket.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void failed(Throwable exc, Object attachment) {
    if (exc instanceof AsynchronousCloseException) {
        complete(-1);
        return;
    }
    completeExceptionally(exc);
}
 
Example #10
Source File: NamedPipeSocket.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void failed(Throwable exc, Object attachment) {
    if (exc instanceof AsynchronousCloseException) {
        complete(-1);
        return;
    }
    completeExceptionally(exc);
}
 
Example #11
Source File: AsynchronousCloseExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests {@link java.nio.channels.AsynchronousCloseException#AsynchronousCloseException()}
 */
public void test_Constructor() {
    AsynchronousCloseException e = new AsynchronousCloseException();
    assertNull(e.getMessage());
    assertNull(e.getLocalizedMessage());
    assertNull(e.getCause());
}
 
Example #12
Source File: AsynchronousOverflowTask.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
     * These are all good indicators that the data service was shutdown.
     */
    static protected boolean isNormalShutdown(
            final ResourceManager resourceManager, final Throwable t) {

        if (Thread.interrupted()) {
            // Note: interrupt status of thread was cleared.
            return true;
        }
        
        if (!resourceManager.isRunning()
                || !resourceManager.getConcurrencyManager()
                        .isOpen()
                || InnerCause.isInnerCause(t,
                        InterruptedException.class)
// Note: cancelled indicates that overflow was timed out.
//                || InnerCause.isInnerCause(t,
//                        CancellationException.class)
                || InnerCause.isInnerCause(t,
                        ClosedByInterruptException.class)
                || InnerCause.isInnerCause(t,
                        ClosedChannelException.class)
                || InnerCause.isInnerCause(t,
                        AsynchronousCloseException.class)) {
            
            return true;
            
        }
        
        return false;
            
    }
 
Example #13
Source File: JimfsFileChannel.java    From jimfs with Apache License 2.0 5 votes vote down vote up
/**
 * Ends a blocking operation, throwing an exception if the thread was interrupted while blocking
 * or if the channel was closed from another thread.
 */
private void endBlocking(boolean completed) throws AsynchronousCloseException {
  synchronized (blockingThreads) {
    blockingThreads.remove(Thread.currentThread());
  }
  end(completed);
}
 
Example #14
Source File: CloseableReferenceCount.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Decrement the reference count, checking to make sure that the
 * CloseableReferenceCount is not closed.
 *
 * @throws AsynchronousCloseException  If the status is closed.
 */
public void unreferenceCheckClosed() throws ClosedChannelException {
  int newVal = status.decrementAndGet();
  if ((newVal & STATUS_CLOSED_MASK) != 0) {
    throw new AsynchronousCloseException();
  }
}
 
Example #15
Source File: JimfsAsynchronousFileChannelTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
/**
 * Assert that the future fails, with the failure caused by either {@code
 * AsynchronousCloseException} or (rarely) {@code ClosedChannelException}.
 */
private static void assertAsynchronousClose(Future<?> future) throws Throwable {
  try {
    future.get(10, SECONDS);
    fail("no exception was thrown");
  } catch (ExecutionException expected) {
    Throwable t = expected.getCause();
    if (!(t instanceof AsynchronousCloseException || t instanceof ClosedChannelException)) {
      fail(
          "expected AsynchronousCloseException (or in rare cases ClosedChannelException); got "
              + t);
    }
  }
}
 
Example #16
Source File: CloseableReferenceCount.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Decrement the reference count, checking to make sure that the
 * CloseableReferenceCount is not closed.
 *
 * @throws AsynchronousCloseException  If the status is closed.
 */
public void unreferenceCheckClosed() throws ClosedChannelException {
  int newVal = status.decrementAndGet();
  if ((newVal & STATUS_CLOSED_MASK) != 0) {
    throw new AsynchronousCloseException();
  }
}
 
Example #17
Source File: ConnectProcessor.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void processOnce() throws IOException {
    // set status of query to OK.
    ctx.getState().reset();
    executor = null;

    // reset sequence id of MySQL protocol
    final MysqlChannel channel = ctx.getMysqlChannel();
    channel.setSequenceId(0);
    // read packet from channel
    try {
        packetBuf = channel.fetchOnePacket();
        if (packetBuf == null) {
            logger.warn("Null packet received from network. remote: {}", channel.getRemote());
            throw new IOException("Error happened when receiving packet.");
        }
    } catch (AsynchronousCloseException e) {
        // when this happened, timeout checker close this channel
        // killed flag in ctx has been already set, just return
        return;
    }

    // dispatch
    dispatch();
    // finalize
    finalizeCommand();

    ctx.setCommand(MysqlCommand.COM_SLEEP);
}
 
Example #18
Source File: ServerSocketChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the end of an I/O operation that may have blocked.
 *
 * @throws AsynchronousCloseException if the channel was closed due to this
 * thread being interrupted on a blocking I/O operation.
 */
private void end(boolean blocking, boolean completed)
    throws AsynchronousCloseException
{
    if (blocking) {
        synchronized (stateLock) {
            thread = 0;
            if (state == ST_CLOSING) {
                tryFinishClose();
            }
        }
        end(completed);
    }
}
 
Example #19
Source File: JimfsFileChannelTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsynchronousClose() throws Exception {
  RegularFile file = regularFile(10);
  final FileChannel channel = channel(file, READ, WRITE);

  file.writeLock().lock(); // ensure all operations on the channel will block

  ExecutorService executor = Executors.newCachedThreadPool();

  CountDownLatch latch = new CountDownLatch(BLOCKING_OP_COUNT);
  List<Future<?>> futures = queueAllBlockingOperations(channel, executor, latch);

  // wait for all the threads to have started running
  latch.await();
  // then ensure time for operations to start blocking
  Uninterruptibles.sleepUninterruptibly(20, MILLISECONDS);

  // close channel on this thread
  channel.close();

  // the blocking operations are running on different threads, so they all get
  // AsynchronousCloseException
  for (Future<?> future : futures) {
    try {
      future.get();
      fail();
    } catch (ExecutionException expected) {
      assertWithMessage("blocking thread exception")
          .that(expected.getCause())
          .isInstanceOf(AsynchronousCloseException.class);
    }
  }
}
 
Example #20
Source File: SocketChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
public long write(ByteBuffer[] srcs, int offset, int length)
    throws IOException
{
    Objects.checkFromIndexSize(offset, length, srcs.length);

    writeLock.lock();
    try {
        boolean blocking = isBlocking();
        long n = 0;
        try {
            beginWrite(blocking);
            n = IOUtil.write(fd, srcs, offset, length, nd);
            if (blocking) {
                while (IOStatus.okayToRetry(n) && isOpen()) {
                    park(Net.POLLOUT);
                    n = IOUtil.write(fd, srcs, offset, length, nd);
                }
            }
        } finally {
            endWrite(blocking, n > 0);
            if (n <= 0 && isOutputClosed)
                throw new AsynchronousCloseException();
        }
        return IOStatus.normalize(n);
    } finally {
        writeLock.unlock();
    }
}
 
Example #21
Source File: SocketChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
public int write(ByteBuffer buf) throws IOException {
    Objects.requireNonNull(buf);

    writeLock.lock();
    try {
        boolean blocking = isBlocking();
        int n = 0;
        try {
            beginWrite(blocking);
            n = IOUtil.write(fd, buf, -1, nd);
            if (blocking) {
                while (IOStatus.okayToRetry(n) && isOpen()) {
                    park(Net.POLLOUT);
                    n = IOUtil.write(fd, buf, -1, nd);
                }
            }
        } finally {
            endWrite(blocking, n > 0);
            if (n <= 0 && isOutputClosed)
                throw new AsynchronousCloseException();
        }
        return IOStatus.normalize(n);
    } finally {
        writeLock.unlock();
    }
}
 
Example #22
Source File: SocketChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the end of a write operation that may have blocked.
 *
 * @throws AsynchronousCloseException if the channel was closed due to this
 * thread being interrupted on a blocking write operation.
 */
private void endWrite(boolean blocking, boolean completed)
    throws AsynchronousCloseException
{
    if (blocking) {
        synchronized (stateLock) {
            writerThread = 0;
            if (state == ST_CLOSING) {
                tryFinishClose();
            }
        }
        // remove hook for Thread.interrupt
        end(completed);
    }
}
 
Example #23
Source File: SocketChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the end of a read operation that may have blocked.
 *
 * @throws AsynchronousCloseException if the channel was closed due to this
 * thread being interrupted on a blocking read operation.
 */
private void endRead(boolean blocking, boolean completed)
    throws AsynchronousCloseException
{
    if (blocking) {
        synchronized (stateLock) {
            readerThread = 0;
            if (state == ST_CLOSING) {
                tryFinishClose();
            }
        }
        // remove hook for Thread.interrupt
        end(completed);
    }
}
 
Example #24
Source File: DatagramChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the end of a write operation that may have blocked.
 *
 * @throws AsynchronousCloseException if the channel was closed asynchronously
 */
private void endWrite(boolean blocking, boolean completed)
    throws AsynchronousCloseException
{
    if (blocking) {
        synchronized (stateLock) {
            writerThread = 0;
            if (state == ST_CLOSING) {
                tryFinishClose();
            }
        }
        // remove hook for Thread.interrupt
        end(completed);
    }
}
 
Example #25
Source File: DatagramChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the end of a read operation that may have blocked.
 *
 * @throws AsynchronousCloseException if the channel was closed asynchronously
 */
private void endRead(boolean blocking, boolean completed)
    throws AsynchronousCloseException
{
    if (blocking) {
        synchronized (stateLock) {
            readerThread = 0;
            if (state == ST_CLOSING) {
                tryFinishClose();
            }
        }
        // remove hook for Thread.interrupt
        end(completed);
    }
}
 
Example #26
Source File: ReadHandler.java    From oxygen with Apache License 2.0 5 votes vote down vote up
@Override
public void failed(Throwable exc, ByteBuffer buffer) {
  if (!(channelContext.isClosed() && exc instanceof AsynchronousCloseException)) {
    log.error("{} read error", channelContext, exc);
  }
  channelContext.close();
}
 
Example #27
Source File: JimfsFileChannelTest.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Test
public void testCloseByInterrupt() throws Exception {
  RegularFile file = regularFile(10);
  final FileChannel channel = channel(file, READ, WRITE);

  file.writeLock().lock(); // ensure all operations on the channel will block

  ExecutorService executor = Executors.newCachedThreadPool();

  final CountDownLatch threadStartLatch = new CountDownLatch(1);
  final SettableFuture<Throwable> interruptException = SettableFuture.create();

  // This thread, being the first to run, will be blocking on the interruptible lock (the byte
  // file's write lock) and as such will be interrupted properly... the other threads will be
  // blocked on the lock that guards the position field and the specification that only one method
  // on the channel will be in progress at a time. That lock is not interruptible, so we must
  // interrupt this thread.
  Thread thread =
      new Thread(
          new Runnable() {
            @Override
            public void run() {
              threadStartLatch.countDown();
              try {
                channel.write(ByteBuffer.allocate(20));
                interruptException.set(null);
              } catch (Throwable e) {
                interruptException.set(e);
              }
            }
          });
  thread.start();

  // let the thread start running
  threadStartLatch.await();
  // then ensure time for thread to start blocking on the write lock
  Uninterruptibles.sleepUninterruptibly(10, MILLISECONDS);

  CountDownLatch blockingStartLatch = new CountDownLatch(BLOCKING_OP_COUNT);
  List<Future<?>> futures = queueAllBlockingOperations(channel, executor, blockingStartLatch);

  // wait for all blocking threads to start
  blockingStartLatch.await();
  // then ensure time for the operations to start blocking
  Uninterruptibles.sleepUninterruptibly(20, MILLISECONDS);

  // interrupting this blocking thread closes the channel and makes all the other threads
  // throw AsynchronousCloseException... the operation on this thread should throw
  // ClosedByInterruptException
  thread.interrupt();

  // get the exception that caused the interrupted operation to terminate
  assertWithMessage("interrupted thread exception")
      .that(interruptException.get(200, MILLISECONDS))
      .isInstanceOf(ClosedByInterruptException.class);

  // check that each other thread got AsynchronousCloseException (since the interrupt, on a
  // different thread, closed the channel)
  for (Future<?> future : futures) {
    try {
      future.get();
      fail();
    } catch (ExecutionException expected) {
      assertWithMessage("blocking thread exception")
          .that(expected.getCause())
          .isInstanceOf(AsynchronousCloseException.class);
    }
  }
}
 
Example #28
Source File: AbstractInterruptibleChannelTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
void superEnd(boolean completed) throws AsynchronousCloseException {
    super.end(completed);
}
 
Example #29
Source File: AsynchronousCloseExceptionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @tests serialization/deserialization compatibility with RI.
 */
public void testSerializationCompatibility() throws Exception {

    SerializationTest.verifyGolden(this, new AsynchronousCloseException());
}
 
Example #30
Source File: AsynchronousCloseExceptionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @tests serialization/deserialization compatibility.
 */
public void testSerializationSelf() throws Exception {

    SerializationTest.verifySelf(new AsynchronousCloseException());
}