use of java.nio.channels.ClosedChannelException in project jeromq by zeromq.
the class ZMQ method poll.
/**
* Polling on items with given selector
* CAUTION: This could be affected by jdk epoll bug
*
* @param selector Open and reuse this selector and do not forget to close when it is not used.
* @param items
* @param count
* @param timeout
* @return number of events
*/
public static int poll(Selector selector, PollItem[] items, int count, long timeout) {
if (items == null) {
throw new IllegalArgumentException();
}
if (count == 0) {
if (timeout <= 0) {
return 0;
}
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
}
return 0;
}
long now = 0L;
long end = 0L;
HashMap<SelectableChannel, SelectionKey> saved = new HashMap<SelectableChannel, SelectionKey>();
for (SelectionKey key : selector.keys()) {
if (key.isValid()) {
saved.put(key.channel(), key);
}
}
for (int i = 0; i < count; i++) {
PollItem item = items[i];
if (item == null) {
continue;
}
// mailbox channel if ZMQ socket
SelectableChannel ch = item.getChannel();
SelectionKey key = saved.remove(ch);
if (key != null) {
if (key.interestOps() != item.interestOps()) {
key.interestOps(item.interestOps());
}
key.attach(item);
} else {
try {
ch.register(selector, item.interestOps(), item);
} catch (ClosedChannelException e) {
throw new ZError.IOException(e);
}
}
}
if (!saved.isEmpty()) {
for (SelectionKey deprecated : saved.values()) {
deprecated.cancel();
}
}
boolean firstPass = true;
int nevents = 0;
int ready;
while (true) {
// Compute the timeout for the subsequent poll.
long waitMillis;
if (firstPass) {
waitMillis = 0L;
} else if (timeout < 0L) {
waitMillis = -1L;
} else {
waitMillis = end - now;
}
// Wait for events.
try {
int rc = 0;
if (waitMillis < 0) {
rc = selector.select(0);
} else if (waitMillis == 0) {
rc = selector.selectNow();
} else {
rc = selector.select(waitMillis);
}
for (SelectionKey key : selector.keys()) {
PollItem item = (PollItem) key.attachment();
ready = item.readyOps(key, rc);
if (ready < 0) {
return -1;
}
if (ready > 0) {
nevents++;
}
}
selector.selectedKeys().clear();
} catch (IOException e) {
throw new ZError.IOException(e);
}
// If timeout is zero, exit immediately whether there are events or not.
if (timeout == 0) {
break;
}
if (nevents > 0) {
break;
}
// If timeout is infinite we can just loop until we get some events.
if (timeout < 0) {
if (firstPass) {
firstPass = false;
}
continue;
}
// when the polling should time out.
if (firstPass) {
now = Clock.nowMS();
end = now + timeout;
if (now == end) {
break;
}
firstPass = false;
continue;
}
// Find out whether timeout have expired.
now = Clock.nowMS();
if (now >= end) {
break;
}
}
return nevents;
}
use of java.nio.channels.ClosedChannelException in project async-http-client by AsyncHttpClient.
the class AsyncHttpClientHandler method exceptionCaught.
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
Throwable cause = getCause(e);
if (cause instanceof PrematureChannelClosureException || cause instanceof ClosedChannelException)
return;
Channel channel = ctx.channel();
NettyResponseFuture<?> future = null;
logger.debug("Unexpected I/O exception on channel {}", channel, cause);
try {
Object attribute = Channels.getAttribute(channel);
if (attribute instanceof StreamedResponsePublisher) {
ctx.fireExceptionCaught(e);
// setting `attribute` to be the underlying future so that the
// retry logic can kick-in
attribute = ((StreamedResponsePublisher) attribute).future();
}
if (attribute instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) attribute;
future.attachChannel(null, false);
future.touch();
if (cause instanceof IOException) {
// FIXME why drop the original exception and throw a new one?
if (hasIOExceptionFilters) {
if (!requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel)) {
// Close the channel so the recovering can occurs.
Channels.silentlyCloseChannel(channel);
}
return;
}
}
if (StackTraceInspector.recoverOnReadOrWriteException(cause)) {
logger.debug("Trying to recover from dead Channel: {}", channel);
future.pendingException = cause;
return;
}
} else if (attribute instanceof OnLastHttpContentCallback) {
future = OnLastHttpContentCallback.class.cast(attribute).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null)
try {
logger.debug("Was unable to recover Future: {}", future);
requestSender.abort(channel, future, cause);
handleException(future, e);
} catch (Throwable t) {
logger.error(t.getMessage(), t);
}
channelManager.closeChannel(channel);
// FIXME not really sure
// ctx.fireChannelRead(e);
Channels.silentlyCloseChannel(channel);
}
use of java.nio.channels.ClosedChannelException in project jeromq by zeromq.
the class Poller method run.
@Override
public void run() {
int returnsImmediately = 0;
while (!stopping) {
// Execute any due timers.
long timeout = executeTimers();
while (retired.compareAndSet(true, false)) {
Iterator<Map.Entry<SelectableChannel, PollSet>> it = fdTable.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<SelectableChannel, PollSet> entry = it.next();
SelectableChannel ch = entry.getKey();
PollSet pollset = entry.getValue();
if (pollset.key == null) {
try {
pollset.key = ch.register(selector, pollset.ops, pollset.handler);
} catch (ClosedChannelException e) {
}
}
if (pollset.cancelled || !ch.isOpen()) {
if (pollset.key != null) {
pollset.key.cancel();
}
it.remove();
}
}
}
// Wait for events.
int rc;
long start = System.currentTimeMillis();
try {
rc = selector.select(timeout);
} catch (IOException e) {
throw new ZError.IOException(e);
}
if (rc == 0) {
// Guess JDK epoll bug
if (timeout == 0 || System.currentTimeMillis() - start < timeout / 2) {
returnsImmediately++;
} else {
returnsImmediately = 0;
}
if (returnsImmediately > 10) {
rebuildSelector();
returnsImmediately = 0;
}
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
IPollEvents evt = (IPollEvents) key.attachment();
it.remove();
try {
if (key.isReadable()) {
evt.inEvent();
} else if (key.isAcceptable()) {
evt.acceptEvent();
} else if (key.isConnectable()) {
evt.connectEvent();
}
if (key.isWritable()) {
evt.outEvent();
}
} catch (CancelledKeyException e) {
// channel might have been closed
}
}
}
stopped = true;
}
use of java.nio.channels.ClosedChannelException in project jdk8u_jdk by JetBrains.
the class Receive method doTest.
void doTest(SocketAddress peerAddress) {
SctpChannel channel = null;
ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
MessageInfo info;
try {
channel = SctpChannel.open();
ReceiveNotificationHandler handler = new ReceiveNotificationHandler(channel);
/* TEST 1: Verify NotYetConnectedException thrown */
try {
channel.receive(buffer, null, handler);
fail("should have thrown NotYetConnectedException");
} catch (NotYetConnectedException unused) {
pass();
} catch (IOException ioe) {
unexpected(ioe);
}
channel.connect(peerAddress);
/* TEST 2: receive small message */
do {
debug("Test 2: invoking receive");
info = channel.receive(buffer, null, handler);
if (info == null) {
fail("unexpected null from receive");
return;
}
} while (!info.isComplete());
buffer.flip();
check(handler.receivedCommUp(), "SCTP_COMM_UP not received");
check(info != null, "info is null");
check(info.address() != null, "address is null");
check(info.association() != null, "association is null");
check(info.isComplete(), "message is not complete");
check(info.isUnordered() != true, "message should not be unordered");
check(info.streamNumber() >= 0, "invalid stream number");
check(info.payloadProtocolID() == PPID, "PPID incorrect");
check(info.bytes() == Util.SMALL_MESSAGE.getBytes("ISO-8859-1").length, "bytes received not equal to message length");
check(info.bytes() == buffer.remaining(), "bytes != remaining");
check(Util.compare(buffer, Util.SMALL_MESSAGE), "received message not the same as sent message");
buffer.clear();
/* TEST 3: receive large message */
do {
debug("Test 3: invoking receive");
info = channel.receive(buffer, null, handler);
if (info == null) {
fail("unexpected null from receive");
return;
}
} while (!info.isComplete());
buffer.flip();
check(info != null, "info is null");
check(info.address() != null, "address is null");
check(info.association() != null, "association is null");
check(info.isComplete(), "message is not complete");
check(info.isUnordered() != true, "message should not be unordered");
check(info.streamNumber() >= 0, "invalid stream number");
check(info.bytes() == Util.LARGE_MESSAGE.getBytes("ISO-8859-1").length, "bytes received not equal to message length");
check(info.bytes() == buffer.remaining(), "bytes != remaining");
check(Util.compare(buffer, Util.LARGE_MESSAGE), "received message not the same as sent message");
buffer.clear();
/* TEST 4: EOF */
// buffer position 0
buffer.clear();
info = channel.receive(buffer, null, handler);
check(info != null, "info is null");
check(info.bytes() == -1, "should have received EOF");
check(buffer.position() == 0, "buffer position should be unchanged");
/* TEST 5: ClosedChannelException */
channel.close();
try {
channel.receive(buffer, null, null);
fail("should have thrown ClosedChannelException");
} catch (ClosedChannelException cce) {
pass();
} catch (IOException ioe) {
unexpected(ioe);
}
handler = null;
/* TEST 6: handler returns RETURN after handling a notification */
ReceiveNotificationHandler handler2 = new ReceiveNotificationHandler(null);
/* HandlerResult.RETURN */
channel = SctpChannel.open(peerAddress, 0, 0);
info = channel.receive(buffer, null, handler2);
check(info == null, "channel should return null");
check(handler2.receivedCommUp(), "SCTP_COMM_UP not received");
check(buffer.position() == 0, "buffer position should be unchanged");
/* TEST 7: Non blocking channel return null if no data */
channel.configureBlocking(false);
info = channel.receive(buffer, null, null);
check(info == null, "non-blocking channel should return null");
check(buffer.position() == 0, "buffer position should be unchanged");
} catch (IOException ioe) {
unexpected(ioe);
} finally {
clientFinishedLatch.countDown();
try {
serverFinishedLatch.await(10L, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
unexpected(ie);
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
unexpected(e);
}
}
}
}
use of java.nio.channels.ClosedChannelException in project opentsdb by OpenTSDB.
the class ConnectionManager method exceptionCaught.
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) {
final Throwable cause = e.getCause();
final Channel chan = ctx.getChannel();
if (cause instanceof ClosedChannelException) {
exceptions_closed.incrementAndGet();
LOG.warn("Attempt to write to closed channel " + chan);
return;
}
if (cause instanceof IOException) {
final String message = cause.getMessage();
if ("Connection reset by peer".equals(message)) {
exceptions_reset.incrementAndGet();
return;
} else if ("Connection timed out".equals(message)) {
exceptions_timeout.incrementAndGet();
// and Java managed to do something *far* worse. That's quite a feat.
return;
} else if (cause instanceof ConnectionRefusedException) {
connections_rejected.incrementAndGet();
if (LOG.isDebugEnabled()) {
LOG.debug("Refusing connection from " + chan, e.getCause());
}
chan.close();
return;
}
}
if (cause instanceof CodecEmbedderException) {
// payload was not compressed as it was announced to be
LOG.warn("Http codec error : " + cause.getMessage());
e.getChannel().close();
return;
}
exceptions_unknown.incrementAndGet();
LOG.error("Unexpected exception from downstream for " + chan, cause);
e.getChannel().close();
}
Aggregations