Java Code Examples for java.nio.channels.SelectableChannel#close()

The following examples show how to use java.nio.channels.SelectableChannel#close() . 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: AbstractNioChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance
 *
 * @param parent            the parent {@link Channel} by which this instance was created. May be {@code null}
 * @param ch                the underlying {@link SelectableChannel} on which it operates
 * @param readInterestOp    the ops to set to receive data from the {@link SelectableChannel}
 */
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
    super(parent);
    this.ch = ch;
    this.readInterestOp = readInterestOp;
    try {
        ch.configureBlocking(false);
    } catch (IOException e) {
        try {
            ch.close();
        } catch (IOException e2) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Failed to close a partially initialized socket.", e2);
            }
        }

        throw new ChannelException("Failed to enter non-blocking mode.", e);
    }
}
 
Example 2
Source File: HeronClient.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
public void handleError(SelectableChannel channel) {
  LOG.info("Handling Error. Cleaning states in HeronClient.");
  contextMap.clear();
  responseMessageMap.clear();
  messageMap.clear();
  socketChannelHelper.clear();
  nioLooper.removeAllInterest(channel);

  try {
    channel.close();
    LOG.info("Successfully closed the channel: " + channel);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to close connection in handleError", e);
  }

  // Since we closed the channel, we set isConnected false
  isConnected = false;
  onError();
}
 
Example 3
Source File: HeronServer.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
public void handleError(SelectableChannel channel) {
  SocketAddress channelAddress = ((SocketChannel) channel).socket().getRemoteSocketAddress();
  LOG.info("Handling error from channel: " + channelAddress);
  SocketChannelHelper helper = activeConnections.get(channel);
  if (helper == null) {
    LOG.severe("Inactive channel had error?");
    return;
  }
  helper.clear();
  LOG.info("Removing all interest on channel: " + channelAddress);
  nioLooper.removeAllInterest(channel);
  try {
    channel.close();
  } catch (IOException e) {
    LOG.severe("Error closing connection in handleError");
  }
  activeConnections.remove(channel);
  onClose((SocketChannel) channel);
}
 
Example 4
Source File: AbstractNioChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
     * Create a new instance
     *
     * @param parent            the parent {@link Channel} by which this instance was created. May be {@code null}
     * @param ch                the underlying {@link SelectableChannel} on which it operates
     * @param readInterestOp    the ops to set to receive data from the {@link SelectableChannel}
     */
    protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
//            设置非阻塞
            ch.configureBlocking(false);
        } catch (IOException e) {
            try {
                ch.close();
            } catch (IOException e2) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }
    }
 
Example 5
Source File: NetworkManager.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
public synchronized void unregisterAction(ChannelAction action) throws IOException, InterruptedException
{
  ChannelConfiguration channelConfiguration = action.channelConfiguration;
  SelectableChannel channel = channelConfiguration.channel;
  if (channelConfiguration != null) {
    channelConfiguration.actions.remove(action);
    if (channelConfiguration.actions.size() == 0) {
      ConnectionInfo connectionInfo = channelConfiguration.connectionInfo;
      channelConfigurations.remove(channel);
      channels.remove(connectionInfo);
      channel.close();
    }
  }
  if (channels.size() == 0) {
    stopProcess();
  }
}
 
Example 6
Source File: SelectorTest.java    From cava with Apache License 2.0 6 votes vote down vote up
@Test
void selectorRemovesKeysOnChannelCloseWhenSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  source.close();
  assertTrue(selector.keys().contains(key));

  selector.selectNow();
  assertFalse(selector.keys().contains(key));
}
 
Example 7
Source File: WebSocketServer.java    From Slyther with MIT License 6 votes vote down vote up
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
	// onWebsocketError( conn, ex );// conn may be null here
	if( conn != null ) {
		conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
	} else if( key != null ) {
		SelectableChannel channel = key.channel();
		if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
			try {
				channel.close();
			} catch ( IOException e ) {
				// there is nothing that must be done here
			}
			if( WebSocketImpl.DEBUG )
				System.out.println( "Connection closed because of" + ex );
		}
	}
}
 
Example 8
Source File: WebSocketServer.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
	// onWebsocketError( conn, ex );// conn may be null here
	if( conn != null ) {
		conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
	} else if( key != null ) {
		SelectableChannel channel = key.channel();
		if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
			try {
				channel.close();
			} catch ( IOException e ) {
				// there is nothing that must be done here
			}
			if( WebSocketImpl.DEBUG )
				System.out.println("Connection closed because of " + ex);
		}
	}
}
 
Example 9
Source File: BaseWebSocketServer.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) {
    // onWebsocketError( conn, ex );// conn may be null here
    if (conn != null) {
        conn.closeConnection(CloseFrame.ABNORMAL_CLOSE, ex.getMessage());
    } else if (key != null) {
        SelectableChannel channel = key.channel();
        if (channel != null && channel.isOpen()) { // this could be the case if the
            // IOException ex is a SSLException
            try {
                channel.close();
            } catch (IOException e) {
                // there is nothing that must be done here
            }
            if (WebSocketImpl.DEBUG) {
                System.out.println("Connection closed because of " + ex);
            }
        }
    }
}
 
Example 10
Source File: Server.java    From twister2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleError(SelectableChannel ch) {
  SocketAddress channelAddress = ((SocketChannel) ch).socket().getRemoteSocketAddress();
  LOG.log(Level.FINE, "Connection is closed: " + channelAddress);

  BaseNetworkChannel channel = connectedChannels.get(ch);
  if (channel == null) {
    LOG.warning("Error occurred in non-existing channel");
    return;
  }
  channel.clear();
  progress.removeAllInterest(ch);
  try {
    ch.close();
  } catch (IOException e) {
    LOG.warning("Error closing conection in error handler");
  }
  connectedChannels.remove(ch);
  channelHandler.onClose((SocketChannel) ch);
}
 
Example 11
Source File: Client.java    From twister2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleError(SelectableChannel ch) {
  channel.clear();
  progress.removeAllInterest(ch);

  LOG.log(Level.SEVERE, "Error on channel " + ch);

  try {
    ch.close();
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to close connection in handleError", e);
  }

  isConnected = false;
  connecting = false;
  tryToConnect = false;
  channelHandler.onError(socketChannel, StatusCode.ERROR_CONN);
}
 
Example 12
Source File: SelectorImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
Example 13
Source File: SelectorImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
Example 14
Source File: SelectorImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
Example 15
Source File: SelectorImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
Example 16
Source File: TcpConnectorService.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private void closeConnection(SelectionKey currentKey, boolean allowReconnect, boolean shuttingDown)
{
    Peer client = (TcpConnectorPeer) currentKey.attachment();
    if (client != null)
    {
        connObserver.connectionClosed(client, allowReconnect, shuttingDown);
        try
        {
            if (client.isConnected(false))
            {
                client.connectionClosing();
            }
        }
        catch (CancelledKeyException ignored)
        {
            // connectionClosing() calls interestOps on the selection Key, which may fail
        }
    }

    try
    {
        SelectableChannel channel = currentKey.channel();
        if (channel != null)
        {
            channel.close();
        }
    }
    catch (IOException closeIoExc)
    {
        // If close() fails with an I/O error, the reason may be interesting
        // enough to file an error report
        errorReporter.reportError(closeIoExc);
    }
    currentKey.cancel();
}
 
Example 17
Source File: SelectorTest.java    From cava with Apache License 2.0 5 votes vote down vote up
@Test
void selectorRemovesKeysOnChannelCloseWhileSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  CountDownLatch latch = new CountDownLatch(1);
  Future<?> job = executor.submit(() -> {
    latch.countDown();
    try {
      selector.select();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  });

  latch.await();
  Thread.sleep(100);

  source.close();
  selector.wakeup();
  job.get();
  assertFalse(selector.keys().contains(key));
}
 
Example 18
Source File: SelectorImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private void clearDeferredRegistrations() {
    synchronized (deferredRegistrations) {
        int deferredListSize = deferredRegistrations.size();
        if (orb.transportDebugFlag) {
            dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize);
        }
        for (int i = 0; i < deferredListSize; i++) {
            EventHandler eventHandler =
                (EventHandler)deferredRegistrations.get(i);
            if (orb.transportDebugFlag) {
                dprint(".clearDeferredRegistrations: " + eventHandler);
            }
            SelectableChannel channel = eventHandler.getChannel();
            SelectionKey selectionKey = null;

            try {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations:close channel == "
                            + channel);
                    dprint(".clearDeferredRegistrations:close channel class == "
                            + channel.getClass().getName());
                }
                channel.close();
                selectionKey = eventHandler.getSelectionKey();
                if (selectionKey != null) {
                    selectionKey.cancel();
                    selectionKey.attach(null);
                }
            } catch (IOException ioEx) {
                if (orb.transportDebugFlag) {
                    dprint(".clearDeferredRegistrations: ", ioEx);
                }
            }
        }
        deferredRegistrations.clear();
    }
}
 
Example 19
Source File: SelectorTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void selectorRemovesKeysOnChannelCloseWhileSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  CountDownLatch latch = new CountDownLatch(1);
  Future<?> job = executor.submit(() -> {
    latch.countDown();
    try {
      selector.select();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  });

  latch.await();
  Thread.sleep(100);

  source.close();
  selector.wakeup();
  job.get();
  assertFalse(selector.keys().contains(key));
}
 
Example 20
Source File: NioAcceptor.java    From craft-atom with MIT License 5 votes vote down vote up
private void close(SelectableChannel sc) throws IOException {
	if (sc != null) {
		SelectionKey key = sc.keyFor(selector);
		if (key != null) {
			key.cancel();
		}
		sc.close();
	}
}