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); } } } }
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. } }
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 } } }
public final void sendPacket(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 } } }
public static SelectionKey registerSelector(final Selector selector, final SocketChannel channel, final int op) throws CancelledKeyException, ClosedChannelException { // Register the selector at the channel, so that it will be notified // on the socket's events synchronized (RegisterGate) { // Wakeup the currently blocking reader/writer thread; we have // locked the RegisterGate to prevent the awakened thread to block again selector.wakeup(); // Lock the selector to prevent the waiting worker threads going // into selector.select() which would block the selector. synchronized (selector) { return channel.register(selector, op, null); } } }
@Test(timeout = 30000) public void testValidSelectionKey() throws Exception { final ZooKeeper zk = createZKClient(hostPort, 3000); try { Iterable<ServerCnxn> connections = serverFactory.getConnections(); for (ServerCnxn serverCnxn : connections) { MockNIOServerCnxn mock = new MockNIOServerCnxn((NIOServerCnxn) serverCnxn); // Cancel key ((NIOServerCnxn) serverCnxn).sock.keyFor(((NIOServerCnxnFactory) serverFactory).selector).cancel();; mock.mockSendBuffer(ByteBuffer.allocate(8)); } } catch (CancelledKeyException e) { LOG.error("Exception while sending bytes!", e); Assert.fail(e.toString()); } finally { zk.close(); } }
private void doAsyncWrite(SelectionKey key) throws IOException { Connection connection = (Connection) 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. */ LOG.warn("Exception while changing ops : " + e); } } }
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; } }
/** * Send a message. Whether it's over TCP or UDP is determined by the message flag. * * @param message The message to send. * @throws IOException When a writing error occurs. */ public void send(Message message) throws IOException { if (!isConnected) throw new IOException("Not connected yet. Use connect() first."); try { if (message.isReliable()) { messageQueue.add(message); if (!isConnector) { tcp.socketChannel.keyFor(tcp.selector).interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } else { tcpChannel.keyFor(tcp.selector).interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } else { udp.sendObject(message); } } catch (CancelledKeyException e) { // Client was disconnected. } }
private void processKeyChangeRequests() { KeyChangeRequest keyChangeRequest; if (AsyncGlobals.debug && debug) { Log.fine("processKeyChangeRequests"); } do { keyChangeRequest = keyChangeRequests.poll(); if (keyChangeRequest != null) { try { processKeyChangeRequest(keyChangeRequest); } catch (CancelledKeyException cke) { Log.warning("Ignoring CancelledKeyException"); } } } while (keyChangeRequest != null); }
public SelectionKey interestOps(int ops) { if (cancelled) throw new CancelledKeyException(); if ((ops & ~(channel.validOps())) != 0) throw new IllegalArgumentException("unsupported channel ops"); try { selector.epoll_modify(this, ops); interestOps = ops; } catch (IOException ioe) { throw new IllegalArgumentException(ioe); } return this; }
@Override public void run() { if (selfCancel) { throw new CancelledKeyException(); } if (cancelled) { terminated = true; disposeTimer(); } queue.offer(NEXT); if (enter()) { drainLoop(); } }
@Override public void run() { WindowExactBoundedSubscriber<?> p = parent; if (p.selfCancel) { throw new CancelledKeyException(); } if (!p.cancelled) { p.queue.offer(this); } else { p.terminated = true; p.disposeTimer(); } if (p.enter()) { p.drainLoop(); } }
@Override public void run() { if (selfCancel) { throw new CancelledKeyException(); } if (cancelled) { terminated = true; dispose(); } queue.offer(NEXT); if (enter()) { drainLoop(); } }
@Override public void run() { WindowExactBoundedSubscriber<?> p = parent; if (p.selfCancel) { throw new CancelledKeyException(); } if (!p.cancelled) { p.queue.offer(this); } else { p.terminated = true; p.dispose(); } if (p.enter()) { p.drainLoop(); } }
@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; } } } }
/** * Set one or more SelectionKey bits in the select mask. * * May be called from outside Worker thread * May recursively lock selectorLock_ * * @param op - OP_READ | OP_WRITE: may be 0 just to force wakeup */ private void setInterestOp(int op) { synchronized (selectorLock_) { final SelectionKey key = selectionKey_; if (key != null && key.isValid()) { try { key.interestOps(key.interestOps() | op); /* * We could check that we have actually changed the mask before * invoking a wakeup. The usage pattern, however, is such that * such a check would almost always be true. */ final Selector selector = key.selector(); // Check "isOpen" to avoid Android crash see // https://code.google.com/p/android/issues/detail?id=80785 if (selector.isOpen()) { selector.wakeup(); } } catch (CancelledKeyException e) { // channel has been closed } } } }
private void doAsyncWrite(SelectionKey key) throws IOException { RpcCall call = (RpcCall)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); } } } }
/** * Updates the interest set associated with a selection key. The * old interest is discarded, being replaced by the new one. * * @param sk The key to be updated. * @param newInterest * @throws IOException */ private void changeKeyInterest(SelectionKey sk, int newInterest) throws IOException { /* This method might throw two unchecked exceptions: * 1. IllegalArgumentException - Should never happen. It is a bug if it happens * 2. CancelledKeyException - Might happen if the channel is closed while * a packet is being dispatched. */ try { sk.interestOps(newInterest); } catch (CancelledKeyException cke) { IOException ioe = new IOException("Failed to change channel interest."); ioe.initCause(cke); throw ioe; } }
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(); } } }
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(); } } }
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(); } } }
/** * @tests serialization/deserialization compatibility. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationSelf", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "CancelledKeyException", args = {} ) }) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new CancelledKeyException()); }
/** * @tests serialization/deserialization compatibility with RI. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationGolden", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "CancelledKeyException", args = {} ) }) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new CancelledKeyException()); }
private void dispatch() throws IOException { int n = selector.select(); if (n == 0) return; Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); Connection conn = (Connection) key.attachment(); it.remove(); try { int readyOps = key.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { if (!conn.receive()) continue; } if ((readyOps & SelectionKey.OP_WRITE) != 0) { conn.send(); } } catch (CancelledKeyException e) { conn.close(); } } }