java.nio.channels.Selector.selectedKeys()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(210)

本文整理了Java中java.nio.channels.Selector.selectedKeys()方法的一些代码示例,展示了Selector.selectedKeys()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Selector.selectedKeys()方法的具体详情如下:
包路径:java.nio.channels.Selector
类名称:Selector
方法名:selectedKeys

Selector.selectedKeys介绍

[英]Gets the selection keys whose channels are ready for operation. The set is not thread-safe and no keys may be added to it. Removing keys is allowed.
[中]获取其通道已准备好进行操作的选择键。该设置不是线程安全的,不能向其中添加任何密钥。允许移除密钥。

代码示例

代码示例来源:origin: iluwatar/java-design-patterns

  1. private void eventLoop() throws IOException {
  2. while (true) {
  3. // honor interrupt request
  4. if (Thread.interrupted()) {
  5. break;
  6. }
  7. // honor any pending commands first
  8. processPendingCommands();
  9. /*
  10. * Synchronous event de-multiplexing happens here, this is blocking call which returns when it is possible to
  11. * initiate non-blocking operation on any of the registered channels.
  12. */
  13. selector.select();
  14. /*
  15. * Represents the events that have occurred on registered handles.
  16. */
  17. Set<SelectionKey> keys = selector.selectedKeys();
  18. Iterator<SelectionKey> iterator = keys.iterator();
  19. while (iterator.hasNext()) {
  20. SelectionKey key = iterator.next();
  21. if (!key.isValid()) {
  22. iterator.remove();
  23. continue;
  24. }
  25. processKey(key);
  26. }
  27. keys.clear();
  28. }
  29. }

代码示例来源:origin: apache/activemq

  1. private void fill(int n) throws IOException, ClosedChannelException {
  2. int bytesRead = -1;
  3. if ((n <= 0) || (n <= bb.remaining()))
  4. return;
  5. bb.compact();
  6. n = (bb.remaining() < n ? bb.remaining() : n);
  7. for (;;) {
  8. bytesRead = sc.read(bb);
  9. if (bytesRead == -1)
  10. throw new ClosedChannelException();
  11. n -= bytesRead;
  12. if (n <= 0)
  13. break;
  14. rs.select(0);
  15. rs.selectedKeys().clear();
  16. }
  17. bb.flip();
  18. }
  19. }

代码示例来源:origin: wildfly/wildfly

  1. public static void await(NioXnio nioXnio, SelectableChannel channel, int op, long time, TimeUnit unit) throws IOException {
  2. if (time <= 0) {
  3. await(nioXnio, channel, op);
  4. return;
  5. }
  6. Xnio.checkBlockingAllowed();
  7. final Selector selector = nioXnio.getSelector();
  8. final SelectionKey selectionKey;
  9. try {
  10. selectionKey = channel.register(selector, op);
  11. } catch (ClosedChannelException e) {
  12. return;
  13. }
  14. long timeoutInMillis = unit.toMillis(time);
  15. selector.select(timeoutInMillis == 0 ? 1: timeoutInMillis);
  16. selector.selectedKeys().clear();
  17. if (Thread.currentThread().isInterrupted()) {
  18. throw log.interruptedIO();
  19. }
  20. selectionKey.cancel();
  21. selector.selectNow();
  22. }
  23. }

代码示例来源:origin: com.hazelcast/hazelcast-all

  1. private void acceptLoop() throws IOException {
  2. while (!stop) {
  3. // block until new connection or interruption.
  4. int keyCount = selector.select();
  5. if (isInterrupted()) {
  6. break;
  7. }
  8. if (keyCount == 0) {
  9. continue;
  10. }
  11. Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  12. handleSelectionKeys(it);
  13. }
  14. }

代码示例来源:origin: looly/hutool

  1. /**
  2. * 开始监听
  3. *
  4. * @throws IOException IO异常
  5. */
  6. private void doListen() throws IOException {
  7. while (0 != this.selector.select()) {
  8. // 返回已选择键的集合
  9. final Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
  10. while (keyIter.hasNext()) {
  11. handle(keyIter.next());
  12. keyIter.remove();
  13. }
  14. }
  15. }

代码示例来源:origin: hazelcast/hazelcast-jet

  1. private void acceptLoop() throws IOException {
  2. while (!stop) {
  3. // block until new connection or interruption.
  4. int keyCount = selector.select();
  5. if (isInterrupted()) {
  6. break;
  7. }
  8. if (keyCount == 0) {
  9. continue;
  10. }
  11. Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  12. handleSelectionKeys(it);
  13. }
  14. }

代码示例来源:origin: alibaba/cobar

  1. @Override
  2. public void run() {
  3. final Selector selector = this.selector;
  4. for (;;) {
  5. ++acceptCount;
  6. try {
  7. selector.select(1000L);
  8. Set<SelectionKey> keys = selector.selectedKeys();
  9. try {
  10. for (SelectionKey key : keys) {
  11. if (key.isValid() && key.isAcceptable()) {
  12. accept();
  13. } else {
  14. key.cancel();
  15. }
  16. }
  17. } finally {
  18. keys.clear();
  19. }
  20. } catch (Throwable e) {
  21. LOGGER.warn(getName(), e);
  22. }
  23. }
  24. }

代码示例来源:origin: wildfly/wildfly

  1. public static void await(NioXnio nioXnio, SelectableChannel channel, int op) throws IOException {
  2. if (NioXnio.IS_HP_UX) {
  3. // HP-UX has buggy write wakeup semantics
  4. await(nioXnio, channel, op, 1, TimeUnit.SECONDS);
  5. return;
  6. }
  7. Xnio.checkBlockingAllowed();
  8. final Selector selector = nioXnio.getSelector();
  9. final SelectionKey selectionKey;
  10. try {
  11. selectionKey = channel.register(selector, op);
  12. } catch (ClosedChannelException e) {
  13. return;
  14. }
  15. selector.select();
  16. selector.selectedKeys().clear();
  17. if (Thread.currentThread().isInterrupted()) {
  18. throw log.interruptedIO();
  19. }
  20. selectionKey.cancel();
  21. selector.selectNow();
  22. }

代码示例来源:origin: looly/hutool

  1. /**
  2. * 开始监听
  3. *
  4. * @throws IOException IO异常
  5. */
  6. private void doListen() throws IOException {
  7. while (0 != this.selector.select()) {
  8. // 返回已选择键的集合
  9. final Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
  10. while (keyIter.hasNext()) {
  11. handle(keyIter.next());
  12. keyIter.remove();
  13. }
  14. }
  15. }

代码示例来源:origin: apache/incubator-gobblin

  1. @Override
  2. public void run() {
  3. try {
  4. Tunnel.this.server.register(this.selector, SelectionKey.OP_ACCEPT,
  5. ExecutorsUtils.loggingDecorator(new AcceptHandler(Tunnel.this.server, this.selector, Tunnel.this.config)));
  6. while (!Thread.interrupted()) {
  7. this.selector.select();
  8. Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
  9. for (SelectionKey selectionKey : selectionKeys) {
  10. dispatch(selectionKey);
  11. }
  12. selectionKeys.clear();
  13. }
  14. } catch (IOException ioe) {
  15. LOG.error("Unhandled IOException. Tunnel will close", ioe);
  16. }
  17. LOG.info("Closing tunnel");
  18. }

代码示例来源:origin: code4craft/netty-learning

  1. public void run() {
  2. try {
  3. while (!Thread.interrupted()) {
  4. //循环,等待事件
  5. selector.select();
  6. Set selected = selector.selectedKeys();
  7. Iterator it = selected.iterator();
  8. while (it.hasNext())
  9. //调用handler,处理事件
  10. dispatch((SelectionKey) (it.next()));
  11. selected.clear();
  12. }
  13. } catch (IOException ex) { /* ... */
  14. }
  15. }

代码示例来源:origin: apache/nifi

  1. private void selectSocketChannelKeys() throws IOException {
  2. // once a channel associated with a key in this selector is 'ready', it causes this select to immediately return.
  3. // thus, for each trip through the run() we only get hit with one real timeout...the one in selectServerSocketKeys.
  4. int numSelected = socketChannelSelector.select(timeout);
  5. if (numSelected == 0) {
  6. return;
  7. }
  8. for (SelectionKey socketChannelKey : socketChannelSelector.selectedKeys()) {
  9. final SelectableChannel channel = socketChannelKey.channel();
  10. AbstractChannelReader reader = null;
  11. // there are 2 kinds of channels in this selector, both which have their own readers and are executed in their own
  12. // threads. We will get here whenever a new SocketChannel is created due to an incoming connection. However,
  13. // for a DatagramChannel we don't want to create a new reader unless it is a new DatagramChannel. The only
  14. // way to tell if it's new is the lack of an attachment.
  15. if (channel instanceof DatagramChannel && socketChannelKey.attachment() == null) {
  16. reader = new DatagramChannelReader(UUID.randomUUID().toString(), socketChannelKey, emptyBuffers, factory, readSingleDatagram);
  17. socketChannelKey.attach(reader);
  18. final ScheduledFuture<?> readerFuture = executor.scheduleWithFixedDelay(reader, 10L, channelReaderFrequencyMilliseconds.get(),
  19. TimeUnit.MILLISECONDS);
  20. reader.setScheduledFuture(readerFuture);
  21. }
  22. if (reader != null && LOGGER.isDebugEnabled()) {
  23. LOGGER.debug(this + " New Connection established. Server channel: " + channel + " Reader: " + reader);
  24. }
  25. }
  26. }

代码示例来源:origin: netty/netty

  1. Iterator<SelectionKey> i = selectedKeys.iterator();
  2. for (;;) {
  3. final SelectionKey k = i.next();
  4. final Object a = k.attachment();
  5. i.remove();
  6. if (!i.hasNext()) {
  7. break;
  8. selectedKeys = selector.selectedKeys();
  9. break;
  10. } else {
  11. i = selectedKeys.iterator();

代码示例来源:origin: alibaba/cobar

  1. @Override
  2. public void run() {
  3. final Selector selector = this.selector;
  4. for (;;) {
  5. ++connectCount;
  6. try {
  7. selector.select(1000L);
  8. connect(selector);
  9. Set<SelectionKey> keys = selector.selectedKeys();
  10. try {
  11. for (SelectionKey key : keys) {
  12. Object att = key.attachment();
  13. if (att != null && key.isValid() && key.isConnectable()) {
  14. finishConnect(key, att);
  15. } else {
  16. key.cancel();
  17. }
  18. }
  19. } finally {
  20. keys.clear();
  21. }
  22. } catch (Throwable e) {
  23. LOGGER.warn(name, e);
  24. }
  25. }
  26. }

代码示例来源:origin: alibaba/nacos

  1. @Override
  2. public void run() {
  3. while (true) {
  4. try {
  5. processTask();
  6. int readyCount = selector.selectNow();
  7. if (readyCount <= 0) {
  8. continue;
  9. }
  10. Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
  11. while (iter.hasNext()) {
  12. SelectionKey key = iter.next();
  13. iter.remove();
  14. NIO_EXECUTOR.execute(new PostProcessor(key));
  15. }
  16. } catch (Throwable e) {
  17. SRV_LOG.error("[HEALTH-CHECK] error while processing NIO task", e);
  18. }
  19. }
  20. }

代码示例来源:origin: alibaba/cobar

  1. ++reactCount;
  2. try {
  3. selector.select(1000L);
  4. register(selector);
  5. Set<SelectionKey> keys = selector.selectedKeys();
  6. try {
  7. for (SelectionKey key : keys) {

代码示例来源:origin: apache/zookeeper

  1. private void select() {
  2. try {
  3. selector.select();
  4. Iterator<SelectionKey> selectedKeys =
  5. selector.selectedKeys().iterator();
  6. while (!stopped && selectedKeys.hasNext()) {
  7. SelectionKey key = selectedKeys.next();
  8. selectedKeys.remove();
  9. if (!key.isValid()) {
  10. continue;
  11. }
  12. if (key.isAcceptable()) {
  13. if (!doAccept()) {
  14. // If unable to pull a new connection off the accept
  15. // queue, pause accepting to give us time to free
  16. // up file descriptors and so the accept thread
  17. // doesn't spin in a tight loop.
  18. pauseAccept(10);
  19. }
  20. } else {
  21. LOG.warn("Unexpected ops in accept select "
  22. + key.readyOps());
  23. }
  24. }
  25. } catch (IOException e) {
  26. LOG.warn("Ignoring IOException while selecting", e);
  27. }
  28. }

代码示例来源:origin: org.apache.zookeeper/zookeeper

  1. public void run() {
  2. while (!ss.socket().isClosed()) {
  3. try {
  4. selector.select(1000);
  5. Set<SelectionKey> selected;
  6. synchronized (this) {
  7. selected = selector.selectedKeys();

代码示例来源:origin: rapidoid/rapidoid

  1. private void processNonBlocking() {
  2. try {
  3. selector.select(50);
  4. } catch (IOException e) {
  5. Log.error("Select failed!", e);
  6. }
  7. try {
  8. Set<SelectionKey> selectedKeys = selector.selectedKeys();
  9. synchronized (selectedKeys) {
  10. Iterator<?> iter = selectedKeys.iterator();
  11. while (iter.hasNext()) {
  12. SelectionKey key = (SelectionKey) iter.next();
  13. iter.remove();
  14. acceptChannel((ServerSocketChannel) key.channel());
  15. }
  16. }
  17. } catch (ClosedSelectorException e) {
  18. // do nothing
  19. }
  20. }

代码示例来源:origin: wildfly/wildfly

  1. @Override
  2. protected void doConnect(SocketAddress remoteAddress,
  3. SocketAddress localAddress) throws Exception {
  4. if (localAddress != null) {
  5. ch.bind(localAddress);
  6. }
  7. boolean success = false;
  8. try {
  9. ch.connect(remoteAddress);
  10. boolean finishConnect = false;
  11. while (!finishConnect) {
  12. if (connectSelector.select(SO_TIMEOUT) >= 0) {
  13. final Set<SelectionKey> selectionKeys = connectSelector.selectedKeys();
  14. for (SelectionKey key : selectionKeys) {
  15. if (key.isConnectable()) {
  16. selectionKeys.clear();
  17. finishConnect = true;
  18. break;
  19. }
  20. }
  21. selectionKeys.clear();
  22. }
  23. }
  24. success = ch.finishConnect();
  25. } finally {
  26. if (!success) {
  27. doClose();
  28. }
  29. }
  30. }

相关文章