use of java.nio.channels.CancelledKeyException in project tomcat by apache.
the class NioReceiver method socketTimeouts.
protected void socketTimeouts() {
long now = System.currentTimeMillis();
if ((now - lastCheck) < getSelectorTimeout())
return;
//timeout
Selector tmpsel = this.selector.get();
Set<SelectionKey> keys = (isListening() && tmpsel != null) ? tmpsel.keys() : null;
if (keys == null)
return;
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext(); ) {
SelectionKey key = iter.next();
try {
// else
if (key.interestOps() == 0) {
//check for keys that didn't make it in.
ObjectReader ka = (ObjectReader) key.attachment();
if (ka != null) {
long delta = now - ka.getLastAccess();
if (delta > getTimeout() && (!ka.isAccessed())) {
if (log.isWarnEnabled())
log.warn(sm.getString("nioReceiver.threadsExhausted", Integer.valueOf(getTimeout()), Boolean.valueOf(ka.isCancelled()), key, new java.sql.Timestamp(ka.getLastAccess())));
ka.setLastAccess(now);
//key.interestOps(SelectionKey.OP_READ);
}
//end if
} else {
cancelledKey(key);
}
//end if
}
//end if
} catch (CancelledKeyException ckx) {
cancelledKey(key);
}
}
lastCheck = System.currentTimeMillis();
}
use of java.nio.channels.CancelledKeyException in project tomcat by apache.
the class NioReplicationTask method run.
// loop forever waiting for work to do
@Override
public synchronized void run() {
if (buffer == null) {
int size = getRxBufSize();
if (key.channel() instanceof DatagramChannel) {
size = ChannelReceiver.MAX_UDP_SIZE;
}
if ((getOptions() & OPTION_DIRECT_BUFFER) == OPTION_DIRECT_BUFFER) {
buffer = ByteBuffer.allocateDirect(size);
} else {
buffer = ByteBuffer.allocate(size);
}
} else {
buffer.clear();
}
if (key == null) {
// just in case
return;
}
if (log.isTraceEnabled())
log.trace("Servicing key:" + key);
try {
ObjectReader reader = (ObjectReader) key.attachment();
if (reader == null) {
if (log.isTraceEnabled())
log.trace("No object reader, cancelling:" + key);
cancelKey(key);
} else {
if (log.isTraceEnabled())
log.trace("Draining channel:" + key);
drainChannel(key, reader);
}
} catch (Exception e) {
//end expire after a certain time.
if (e instanceof CancelledKeyException) {
//do nothing
} else if (e instanceof IOException) {
//dont spew out stack traces for IO exceptions unless debug is enabled.
if (log.isDebugEnabled())
log.debug("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed[" + e.getMessage() + "].", e);
else
log.warn(sm.getString("nioReplicationTask.unable.drainChannel.ioe", e.getMessage()));
} else if (log.isErrorEnabled()) {
//this is a real error, log it.
log.error(sm.getString("nioReplicationTask.exception.drainChannel"), e);
}
cancelKey(key);
}
key = null;
// done, ready for more, return to pool
getTaskPool().returnWorker(this);
}
use of java.nio.channels.CancelledKeyException in project netty by netty.
the class NioEventLoop method select.
private void select(boolean oldWakenUp) throws IOException {
Selector selector = this.selector;
try {
int selectCnt = 0;
long currentTimeNanos = System.nanoTime();
long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos);
for (; ; ) {
long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L;
if (timeoutMillis <= 0) {
if (selectCnt == 0) {
selector.selectNow();
selectCnt = 1;
}
break;
}
// It might be pended until idle timeout if IdleStateHandler existed in pipeline.
if (hasTasks() && wakenUp.compareAndSet(false, true)) {
selector.selectNow();
selectCnt = 1;
break;
}
int selectedKeys = selector.select(timeoutMillis);
selectCnt++;
if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) {
// - a scheduled task is ready for processing
break;
}
if (Thread.interrupted()) {
// See https://github.com/netty/netty/issues/2426
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely because " + "Thread.currentThread().interrupt() was called. Use " + "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop.");
}
selectCnt = 1;
break;
}
long time = System.nanoTime();
if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) {
// timeoutMillis elapsed without anything selected.
selectCnt = 1;
} else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) {
// The selector returned prematurely many times in a row.
// Rebuild the selector to work around the problem.
logger.warn("Selector.select() returned prematurely {} times in a row; rebuilding Selector {}.", selectCnt, selector);
rebuildSelector();
selector = this.selector;
// Select again to populate selectedKeys.
selector.selectNow();
selectCnt = 1;
break;
}
currentTimeNanos = time;
}
if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) {
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely {} times in a row for Selector {}.", selectCnt - 1, selector);
}
}
} catch (CancelledKeyException e) {
if (logger.isDebugEnabled()) {
logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector {} - JDK bug?", selector, e);
}
// Harmless exception - log anyway
}
}
use of java.nio.channels.CancelledKeyException in project robovm by robovm.
the class AbstractSelectableChannel method register.
/**
* Registers this channel with the specified selector for the specified
* interest set. If the channel is already registered with the selector, the
* {@link SelectionKey interest set} is updated to {@code interestSet} and
* the corresponding selection key is returned. If the channel is not yet
* registered, this method calls the {@code register} method of
* {@code selector} and adds the selection key to this channel's key set.
*
* @param selector
* the selector with which to register this channel.
* @param interestSet
* this channel's {@link SelectionKey interest set}.
* @param attachment
* the object to attach, can be {@code null}.
* @return the selection key for this registration.
* @throws CancelledKeyException
* if this channel is registered but its key has been canceled.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IllegalArgumentException
* if {@code interestSet} is not supported by this channel.
* @throws IllegalBlockingModeException
* if this channel is in blocking mode.
* @throws IllegalSelectorException
* if this channel does not have the same provider as the given
* selector.
*/
@Override
public final SelectionKey register(Selector selector, int interestSet, Object attachment) throws ClosedChannelException {
if (!isOpen()) {
throw new ClosedChannelException();
}
if (!((interestSet & ~validOps()) == 0)) {
throw new IllegalArgumentException("no valid ops in interest set: " + interestSet);
}
synchronized (blockingLock) {
if (isBlocking) {
throw new IllegalBlockingModeException();
}
if (!selector.isOpen()) {
if (interestSet == 0) {
// throw ISE exactly to keep consistency
throw new IllegalSelectorException();
}
// throw NPE exactly to keep consistency
throw new NullPointerException("selector not open");
}
SelectionKey key = keyFor(selector);
if (key == null) {
key = ((AbstractSelector) selector).register(this, interestSet, attachment);
keyList.add(key);
} else {
if (!key.isValid()) {
throw new CancelledKeyException();
}
key.interestOps(interestSet);
key.attach(attachment);
}
return key;
}
}
use of java.nio.channels.CancelledKeyException in project hs4j by killme2008.
the class Reactor method dispatchEvent.
/**
* Dispatch selected event
*
* @param selectedKeySet
*/
public final void dispatchEvent(Set<SelectionKey> selectedKeySet) {
Iterator<SelectionKey> it = selectedKeySet.iterator();
boolean skipOpRead = false;
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
if (key.attachment() != null) {
controller.closeSelectionKey(key);
} else {
key.cancel();
}
continue;
}
try {
if (key.isValid() && key.isAcceptable()) {
controller.onAccept(key);
continue;
}
if (key.isValid() && (key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
// Remove write interest
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
controller.onWrite(key);
if (!controller.isHandleReadWriteConcurrently()) {
skipOpRead = true;
}
}
if (!skipOpRead && key.isValid() && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
if (!controller.getStatistics().isReceiveOverFlow()) {
// Remove read interest
controller.onRead(key);
} else {
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
}
}
if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
controller.onConnect(key);
}
} catch (CancelledKeyException e) {
// ignore
} catch (RejectedExecutionException e) {
if (key.attachment() instanceof AbstractNioSession) {
((AbstractNioSession) key.attachment()).onException(e);
}
controller.notifyException(e);
if (selector.isOpen()) {
continue;
} else {
break;
}
} catch (Exception e) {
if (key.attachment() instanceof AbstractNioSession) {
((AbstractNioSession) key.attachment()).onException(e);
}
controller.closeSelectionKey(key);
controller.notifyException(e);
log.error("Reactor dispatch events error", e);
if (selector.isOpen()) {
continue;
} else {
break;
}
}
}
}
Aggregations