java.nio.channels.CancelledKeyException Java Examples

The following examples show how to use java.nio.channels.CancelledKeyException. 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: Server.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  Call call = (Call)key.attachment();
  if (call == null) {
    return;
  }
  if (key.channel() != call.connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  synchronized(call.connection.responseQueue) {
    if (processResponse(call.connection.responseQueue, false)) {
      try {
        key.interestOps(0);
      } catch (CancelledKeyException e) {
        /* The Listener/reader might have closed the socket.
         * We don't explicitly cancel the key, so not sure if this will
         * ever fire.
         * This warning could be removed.
         */
        LOG.warn("Exception while changing ops : " + e);
      }
    }
  }
}
 
Example #2
Source File: ConnectionTableNIO.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private void disable()
{
   if (m_enabled)
   {
      try
      {
         m_key.interestOps(0);               // pass zero which means that we are not interested in being
                                             // notified of anything for this channel.
      }
      catch (CancelledKeyException eat)      // If we finished writing and didn't get an exception, then
      {                                      // we probably don't need to throw this exception (if they try to write
                                             // again, we will then throw an exception).
      }
      m_enabled = false;
   }
}
 
Example #3
Source File: MMOConnection.java    From L2jBrasil with GNU General Public License v3.0 6 votes vote down vote up
public final void sendPacket(final SendablePacket<T> sp)
 {
     sp._client = _client;

     if (_pendingClose)
return;
     
     synchronized (getSendQueue())
     {
     	_sendQueue.addLast(sp);
     }

     if (!_sendQueue.isEmpty())
     {
         try
         {
             _selectionKey.interestOps(_selectionKey.interestOps() | SelectionKey.OP_WRITE);
         }
         catch (CancelledKeyException e)
         {
             // ignore
         }
     }
 }
 
Example #4
Source File: MonitorThread.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void processDebuggerActivity(SelectionKey key) {
    Debugger dbg = (Debugger)key.attachment();

    try {
        if (key.isAcceptable()) {
            try {
                acceptNewDebugger(dbg, null);
            } catch (IOException ioe) {
                Log.w("ddms", "debugger accept() failed");
                ioe.printStackTrace();
            }
        } else if (key.isReadable()) {
            processDebuggerData(key);
        } else {
            Log.d("ddm-debugger", "key in unknown state");
        }
    } catch (CancelledKeyException cke) {
        // key has been cancelled we can ignore that.
    }
}
 
Example #5
Source File: Server.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  Call call = (Call)key.attachment();
  if (call == null) {
    return;
  }
  if (key.channel() != call.connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  synchronized(call.connection.responseQueue) {
    if (processResponse(call.connection.responseQueue, false)) {
      try {
        key.interestOps(0);
      } catch (CancelledKeyException e) {
        /* The Listener/reader might have closed the socket.
         * We don't explicitly cancel the key, so not sure if this will
         * ever fire.
         * This warning could be removed.
         */
        LOG.warn("Exception while changing ops : " + e);
      }
    }
  }
}
 
Example #6
Source File: SelectorThread.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private boolean selectionInterestRequiresUpdate(NonBlockingConnection connection)
{
    SelectionTask selectionTask = connection.getSelectionTask();
    if(selectionTask != null)
    {
        final SelectionKey selectionKey = connection.getSocketChannel().keyFor(selectionTask.getSelector());
        int expectedOps = (connection.wantsRead() ? SelectionKey.OP_READ : 0)
                          | (connection.wantsWrite() ? SelectionKey.OP_WRITE : 0);

        try
        {
            return selectionKey == null || !selectionKey.isValid() || selectionKey.interestOps() != expectedOps;
        }
        catch (CancelledKeyException e)
        {
            return true;
        }
    }
    else
    {
        return true;
    }
}
 
Example #7
Source File: Server.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  Call call = (Call)key.attachment();
  if (call == null) {
    return;
  }
  if (key.channel() != call.connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  synchronized(call.connection.responseQueue) {
    if (processResponse(call.connection.responseQueue, false)) {
      try {
        key.interestOps(0);
      } catch (CancelledKeyException e) {
        /* The Listener/reader might have closed the socket.
         * We don't explicitly cancel the key, so not sure if this will
         * ever fire.
         * This warning could be removed.
         */
        LOG.warn("Exception while changing ops : " + e);
      }
    }
  }
}
 
Example #8
Source File: ConnectionTableNIO.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private void disable()
{
   if (m_enabled)
   {
      try
      {
         m_key.interestOps(0);               // pass zero which means that we are not interested in being
                                             // notified of anything for this channel.
      }
      catch (CancelledKeyException eat)      // If we finished writing and didn't get an exception, then
      {                                      // we probably don't need to throw this exception (if they try to write
                                             // again, we will then throw an exception).
      }
      m_enabled = false;
   }
}
 
Example #9
Source File: AbstractNioChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRegister() throws Exception {
    boolean selected = false;
    for (;;) {
        try {
            selectionKey = javaChannel().register(eventLoop().selector, 0, this);
            return;
        } catch (CancelledKeyException e) {
            if (!selected) {
                // Force the Selector to select now as the "canceled" SelectionKey may still be
                // cached and not removed because no Select.select(..) operation was called yet.
                eventLoop().selectNow();
                selected = true;
            } else {
                // We forced a select operation on the selector before but the SelectionKey is still cached
                // for whatever reason. JDK bug ?
                throw e;
            }
        }
    }
}
 
Example #10
Source File: ChannelManagerImpl.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
private void doConnect(long now, Set<SelectionKey> keys) {

		Iterator<SelectionKey> iter = keys.iterator();
		while (iter.hasNext()) {
			SelectionKey key = iter.next();
			try {
				if (key.isConnectable()) {
					MqttChannel channel = (MqttChannel) key.attachment();
					if (!channel.finishConnect()) {
						channelClosed(channel);
						iter.remove();
					}
				}
			} catch (CancelledKeyException e) {
				iter.remove();
			}
		}
	}
 
Example #11
Source File: ChannelManagerImpl.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
private void doRead(long now, Set<SelectionKey> keys) {

		Iterator<SelectionKey> iter = keys.iterator();
		while (iter.hasNext()) {
			SelectionKey key = iter.next();
			try {
				if (key.isReadable()) {
					MqttChannel channel = (MqttChannel) key.attachment();
					if (!channel.read(now)) {
						channelClosed(channel);
						iter.remove();
					}
				}
			} catch (CancelledKeyException e) {
				iter.remove();
			}
		}
	}
 
Example #12
Source File: ChannelManagerImpl.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
private void doWrite(long now, Set<SelectionKey> keys) {

		Iterator<SelectionKey> iter = keys.iterator();
		while (iter.hasNext()) {
			SelectionKey key = iter.next();
			try {
				if (key.isWritable()) {
					MqttChannel channel = (MqttChannel) key.attachment();
					if (!channel.write(now)) {
						channelClosed(channel);
						iter.remove();
					}
				}
			} catch (CancelledKeyException e) {
				iter.remove();
			}
		}
	}
 
Example #13
Source File: SimpleRpcServerResponder.java    From hbase with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  SimpleServerRpcConnection connection = (SimpleServerRpcConnection) key.attachment();
  if (connection == null) {
    throw new IOException("doAsyncWrite: no connection");
  }
  if (key.channel() != connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  if (processAllResponses(connection)) {
    try {
      // We wrote everything, so we don't need to be told when the socket is ready for
      // write anymore.
      key.interestOps(0);
    } catch (CancelledKeyException e) {
      /*
       * The Listener/reader might have closed the socket. We don't explicitly cancel the key, so
       * not sure if this will ever fire. This warning could be removed.
       */
      SimpleRpcServer.LOG.warn("Exception while changing ops : " + e);
    }
  }
}
 
Example #14
Source File: Server.java    From RDFS with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  Call call = (Call)key.attachment();
  if (call == null) {
    return;
  }
  if (key.channel() != call.connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  synchronized(call.connection.responseQueue) {
    if (processResponse(call.connection.responseQueue, false)) {
      try {
        key.interestOps(0);
      } catch (CancelledKeyException e) {
        /* The Listener/reader might have closed the socket.
         * We don't explicitly cancel the key, so not sure if this will
         * ever fire.
         * This warning could be removed.
         */
        LOG.warn("Exception while changing ops : " + e);
      }
    }
  }
}
 
Example #15
Source File: Server.java    From stratosphere with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
	Call call = (Call) key.attachment();
	if (call == null) {
		return;
	}
	if (key.channel() != call.connection.channel) {
		throw new IOException("doAsyncWrite: bad channel");
	}

	synchronized (call.connection.responseQueue) {
		if (processResponse(call.connection.responseQueue, false)) {
			try {
				key.interestOps(0);
			} catch (CancelledKeyException e) {
				/*
				 * The Listener/reader might have closed the socket.
				 * We don't explicitly cancel the key, so not sure if this will
				 * ever fire.
				 * This warning could be removed.
				 */
				LOG.warn("Exception while changing ops : " + e);
			}
		}
	}
}
 
Example #16
Source File: SelectorUtil.java    From android-netty with Apache License 2.0 5 votes vote down vote up
static int select(Selector selector) throws IOException {
	try {
		return selector.select(SELECT_TIMEOUT);
	} catch (CancelledKeyException e) {
		// if (logger.isDebugEnabled()) {
		// logger.debug(
		// CancelledKeyException.class.getSimpleName() +
		// " raised by a Selector - JDK bug?", e);
		// }
		e.printStackTrace();
		// Harmless exception - log anyway
	}
	return -1;
}
 
Example #17
Source File: NioBlockingSelector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void run() {
    SelectionKey sk = ch.keyFor(selector);
    try {
        if (sk == null) {
            if (SelectionKey.OP_WRITE==(ops&SelectionKey.OP_WRITE)) countDown(key.getWriteLatch());
            if (SelectionKey.OP_READ==(ops&SelectionKey.OP_READ))countDown(key.getReadLatch());
        } else {
            if (sk.isValid()) {
                sk.interestOps(sk.interestOps() & (~ops));
                if (SelectionKey.OP_WRITE==(ops&SelectionKey.OP_WRITE)) countDown(key.getWriteLatch());
                if (SelectionKey.OP_READ==(ops&SelectionKey.OP_READ))countDown(key.getReadLatch());
                if (sk.interestOps()==0) {
                    sk.cancel();
                    sk.attach(null);
                }
            }else {
                sk.cancel();
                sk.attach(null);
            }
        }
    }catch (CancelledKeyException cx) {
        if (sk!=null) {
            sk.cancel();
            sk.attach(null);
        }
    }
}
 
Example #18
Source File: WindowsSelectorImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #19
Source File: WindowsSelectorImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #20
Source File: WindowsSelectorImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #21
Source File: NioEventLoop.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
    final NioUnsafe unsafe = ch.unsafe();
    if (!k.isValid()) {
        // close the channel if the key is not valid anymore
        unsafe.close(unsafe.voidPromise());
        return;
    }

    try {
        int readyOps = k.readyOps();
        // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
        // to a spin loop
        if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
            unsafe.read();
            if (!ch.isOpen()) {
                // Connection already closed - no need to handle write.
                return;
            }
        }
        if ((readyOps & SelectionKey.OP_WRITE) != 0) {
            // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
            ch.unsafe().forceFlush();
        }
        if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
            // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
            // See https://github.com/netty/netty/issues/924
            int ops = k.interestOps();
            ops &= ~SelectionKey.OP_CONNECT;
            k.interestOps(ops);

            unsafe.finishConnect();
        }
    } catch (CancelledKeyException ignored) {
        unsafe.close(unsafe.voidPromise());
    }
}
 
Example #22
Source File: AbstractNioChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
    protected void doRegister() throws Exception {
//        渠道监听状态
        boolean selected = false;
        for (;;) {
            try {
//                通道注册到选择器上
                selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
                return;
            } catch (CancelledKeyException e) {
                if (!selected) {
                    // Force the Selector to select now as the "canceled" SelectionKey may still be
                    // cached and not removed because no Select.select(..) operation was called yet.//强制选择器现在选择,因为“已取消”的SelectionKey可能仍然是
//缓存,未删除,因为没有Select.select(..)操作被调用。
//                    开始监听
                    eventLoop().selectNow();
//                    修改选择器的监听状态
                    selected = true;
                } else {
                    // We forced a select operation on the selector before but the SelectionKey is still cached
                    // for whatever reason. JDK bug ?//我们之前在选择器上强制执行了select操作,但是SelectionKey仍然被缓存
//不管什么原因。JDK错误?
                    throw e;
                }
            }
        }
    }
 
Example #23
Source File: SelectionRegistration.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Effectively updates the registration of the
 * {@link #getSelectableChannel()} with the given {@link Selector} for the
 * {@link #getInterestOperations()} operations.
 * 
 * @return The updated selection key or a new one if it was registered
 *         again.
 */
public SelectionKey update() {
    if (this.selectionKey.isValid()) {
        if (isCanceling()) {
            Context.getCurrentLogger().log(Level.FINER,
                    "Cancelling of the selection key requested");
            this.selectionKey.cancel();
        } else {
            try {
                if (Context.getCurrentLogger().isLoggable(Level.FINEST)) {
                    Context.getCurrentLogger()
                            .log(Level.FINEST,
                                    "Update key (old | new) : "
                                            + SelectionRegistration
                                                    .getName(this.selectionKey
                                                            .interestOps())
                                            + " | "
                                            + SelectionRegistration
                                                    .getName(getInterestOperations()));
                }

                this.selectionKey.interestOps(getInterestOperations());
            } catch (CancelledKeyException cke) {
                Context.getCurrentLogger()
                        .log(Level.FINE,
                                "Unable to update a cancelled key, registering again",
                                cke);
                this.selectionKey = register(this.selectionKey.selector());
            }
        }
    } else {
        Context.getCurrentLogger().log(Level.FINE,
                "Invalid key detected, registering again");
        this.selectionKey = register(this.selectionKey.selector());
    }

    return this.selectionKey;
}
 
Example #24
Source File: WebSocketServer.java    From Slyther with MIT License 5 votes vote down vote up
@Override
public final void onWriteDemand( WebSocket w ) {
	WebSocketImpl conn = (WebSocketImpl) w;
	try {
		conn.key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
	} catch ( CancelledKeyException e ) {
		// the thread which cancels key is responsible for possible cleanup
		conn.outQueue.clear();
	}
	selector.wakeup();
}
 
Example #25
Source File: WindowsSelectorImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #26
Source File: NioReceiver.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
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 {
//                if (key.interestOps() == SelectionKey.OP_READ) {
//                    //only timeout sockets that we are waiting for a read from
//                    ObjectReader ka = (ObjectReader) key.attachment();
//                    long delta = now - ka.getLastAccess();
//                    if (delta > (long) getTimeout()) {
//                        cancelledKey(key);
//                    }
//                }
//                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("Channel key is registered, but has had no interest ops for the last "+getTimeout()+" ms. (cancelled:"+ka.isCancelled()+"):"+key+" last access:"+new java.sql.Timestamp(ka.getLastAccess())+" Possible cause: all threads used, perform thread dump");
                            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();
    }
 
Example #27
Source File: NioReplicationTask.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
protected void registerForRead(final SelectionKey key, ObjectReader reader) {
    if ( log.isTraceEnabled() )
        log.trace("Adding key for read event:"+key);
    reader.finish();
    //register our OP_READ interest
    Runnable r = new Runnable() {
        @Override
        public void run() {
            try {
                if (key.isValid()) {
                    // cycle the selector so this key is active again
                    key.selector().wakeup();
                    // resume interest in OP_READ, OP_WRITE
                    int resumeOps = key.interestOps() | SelectionKey.OP_READ;
                    key.interestOps(resumeOps);
                    if ( log.isTraceEnabled() )
                        log.trace("Registering key for read:"+key);
                }
            } catch (CancelledKeyException ckx ) {
                NioReceiver.cancelledKey(key);
                if ( log.isTraceEnabled() )
                    log.trace("CKX Cancelling key:"+key);

            } catch (Exception x) {
                log.error("Error registering key for read:"+key,x);
            }
        }
    };
    receiver.addEvent(r);
}
 
Example #28
Source File: WindowsSelectorImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #29
Source File: WindowsSelectorImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void putEventOps(SelectionKeyImpl sk, int ops) {
    synchronized (closeLock) {
        if (pollWrapper == null)
            throw new ClosedSelectorException();
        // make sure this sk has not been removed yet
        int index = sk.getIndex();
        if (index == -1)
            throw new CancelledKeyException();
        pollWrapper.putEventOps(index, ops);
    }
}
 
Example #30
Source File: BaseWebSocketServer.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final void onWriteDemand(WebSocket w) {
    WebSocketImpl conn = (WebSocketImpl) w;
    try {
        conn.key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    } catch (CancelledKeyException e) {
        // the thread which cancels key is responsible for possible cleanup
        conn.outQueue.clear();
    }
    selector.wakeup();
}