示例#1
0
 public int ready() throws IOException {
   if (descriptor.getChannel() instanceof SelectableChannel) {
     int ready_stat = 0;
     java.nio.channels.Selector sel =
         SelectorFactory.openWithRetryFrom(
             null, ((SelectableChannel) descriptor.getChannel()).provider());
     SelectableChannel selchan = (SelectableChannel) descriptor.getChannel();
     synchronized (selchan.blockingLock()) {
       boolean is_block = selchan.isBlocking();
       try {
         selchan.configureBlocking(false);
         selchan.register(sel, java.nio.channels.SelectionKey.OP_READ);
         ready_stat = sel.selectNow();
         sel.close();
       } catch (Throwable ex) {
       } finally {
         if (sel != null) {
           try {
             sel.close();
           } catch (Exception e) {
           }
         }
         selchan.configureBlocking(is_block);
       }
     }
     return ready_stat;
   } else {
     return newInputStream().available();
   }
 }
示例#2
0
  @Override
  public void release() {
    try {
      mcastObject(null, slaves.length);
      flushBuffers(0);
    } catch (Exception e) {
      log.warn("Failed to send termination to slaves.", e);
    }
    try {
      discoverySelector.close();
    } catch (Throwable e) {
      log.warn("Error closing discovery selector", e);
    }
    try {
      communicationSelector.close();
    } catch (Throwable e) {
      log.warn("Error closing comunication selector", e);
    }
    for (SocketChannel sc : slaves) {
      try {
        sc.socket().close();
      } catch (Throwable e) {
        log.warn("Error closing channel", e);
      }
    }

    try {
      if (serverSocketChannel != null) serverSocketChannel.socket().close();
    } catch (Throwable e) {
      log.warn("Error closing server socket channel", e);
    }
  }
示例#3
0
文件: Reactor.java 项目: checkes/hs4j
  @Override
  public void run() {
    selectorManager.notifyReady();
    while (selectorManager.isStarted() && selector.isOpen()) {
      try {
        beforeSelect();
        wakenUp.set(false);
        long before = -1;
        // Wether to look jvm bug
        if (isNeedLookingJVMBug()) {
          before = System.currentTimeMillis();
        }
        long wait = DEFAULT_WAIT;
        if (nextTimeout > 0) {
          wait = nextTimeout;
        }
        int selected = selector.select(wait);
        if (selected == 0) {
          if (before != -1) {
            lookJVMBug(before, selected, wait);
          }
          selectTries++;
          // check tmeout and idle
          nextTimeout = checkSessionTimeout();
          continue;
        } else {
          selectTries = 0;
        }

      } catch (ClosedSelectorException e) {
        break;
      } catch (IOException e) {
        log.error("Reactor select error", e);
        if (selector.isOpen()) {
          continue;
        } else {
          break;
        }
      }
      Set<SelectionKey> selectedKeys = selector.selectedKeys();
      gate.lock();
      try {
        postSelect(selectedKeys, selector.keys());
        dispatchEvent(selectedKeys);
      } finally {
        gate.unlock();
      }
    }
    if (selector != null) {
      if (selector.isOpen()) {
        try {
          controller.closeChannel(selector);
          selector.close();
        } catch (IOException e) {
          controller.notifyException(e);
          log.error("stop reactor error", e);
        }
      }
    }
  }
示例#4
0
 public static void selectorClose(Selector selector) throws NetSelectorException {
   try {
     selector.close();
   } catch (IOException e) {
     throw new NetSelectorException(e);
   }
 }
 public List<Runnable> shutdownNow() {
   runState = state.SHUTTINGDOWN;
   LOG.info("Commencing immediate shutdown of client: " + this);
   timer.cancel();
   Iterator<GearmanJobServerSession> sessions = sessionsMap.values().iterator();
   while (sessions.hasNext()) {
     GearmanJobServerSession curSession = sessions.next();
     if (!curSession.isInitialized()) {
       continue;
     }
     try {
       curSession.closeSession();
     } catch (Exception e) {
       LOG.warn(
           "Failed to closes session "
               + curSession
               + " while performing immediate shutdown of client "
               + this
               + ". Encountered the following exception "
               + e);
     }
     sessions.remove();
   }
   sessionsMap.clear();
   sessionsMap = null;
   runState = state.TERMINATED;
   try {
     ioAvailable.close();
   } catch (IOException ioe) {
     LOG.warn("Encountered IOException while closing selector for client ", ioe);
   }
   LOG.info("Completed shutdown of client: " + this);
   return new ArrayList<Runnable>();
 }
  /*
   * For the time being this will always return an empty list of
   * exceptions because closeSession does not throw an exception
   */
  private List<Exception> shutDownWorker(boolean completeTasks) {
    LOG.info("Commencing shutdowm of worker " + this);

    ArrayList<Exception> exceptions = new ArrayList<Exception>();

    // This gives any jobs in flight a chance to complete
    if (executorService != null) {
      if (completeTasks) {
        executorService.shutdown();
      } else {
        executorService.shutdownNow();
      }
    }

    for (GearmanJobServerSession sess : sessionMap.values()) {
      sess.closeSession();
    }
    try {
      ioAvailable.close();
    } catch (IOException ioe) {
      LOG.warn("Encountered IOException while closing selector for worker: ", ioe);
    }
    state = State.IDLE;
    LOG.info("Completed shutdowm of worker " + this);

    return exceptions;
  }
示例#7
0
 public void cleanTask() {
   try {
     if (thread != null) {
       thread.join(2000);
       if (thread.isAlive()) {
         // FIXME: remove ASAP
         thread.interrupt();
       }
       thread = null;
     }
   } catch (InterruptedException e) {
     logger.debug("Can not stop thread", e);
   }
   if (selector != null) {
     try {
       selector.close();
     } catch (Exception e) {
       // ignore
     }
     selector = null;
   }
   if (serverSocket != null) {
     try {
       serverSocket.close();
     } catch (Exception e) {
       // ignore
     }
     serverSocket = null;
   }
 }
示例#8
0
 /** 关闭端口选择器 */
 private void shutdown() {
   if (serverSocketChannel != null) {
     try {
       serverSocketChannel.close();
       while (serverSocketChannel.isOpen()) {
         try {
           Thread.sleep(300L);
         } catch (final InterruptedException e) {
           e.printStackTrace();
         }
         serverSocketChannel.close();
       }
       System.out.println("端口关闭成功");
     } catch (IOException e1) {
       System.err.println("端口关闭错误:");
       e1.printStackTrace();
     } finally {
       serverSocketChannel = null;
     }
   }
   // 关闭端口选择器
   if (selector != null) {
     try {
       selector.close();
       System.out.println("端口选择器关闭成功");
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       selector = null;
     }
   }
 }
示例#9
0
 public void run() {
   try {
     sel.close();
   } catch (Throwable th) {
     throw new Error(th);
   }
 }
    private void dispose(Selector localSelector, LinkedBlockingQueue localSelectorTasks) {
      Assert.eval(Thread.currentThread() == this);

      if (localSelector != null) {

        for (Object element : localSelector.keys()) {
          try {
            SelectionKey key = (SelectionKey) element;
            cleanupChannel(key.channel(), null);
          } catch (Exception e) {
            logger.warn("Exception trying to close channel", e);
          }
        }

        try {
          localSelector.close();
        } catch (Exception e) {
          if ((Os.isMac()) && (Os.isUnix()) && (e.getMessage().equals("Bad file descriptor"))) {
            // I can't find a specific bug about this, but I also can't seem to prevent the
            // exception on the Mac.
            // So just logging this as warning.
            logger.warn("Exception trying to close selector: " + e.getMessage());
          } else {
            logger.error("Exception trying to close selector", e);
          }
        }
      }
    }
示例#11
0
  /**
   * Start the server running - accepting connections, receiving messages. If the server is already
   * running, it will not be started again. This method is designed to be called in its own thread
   * and will not return until the server is stopped.
   *
   * @throws RuntimeException if the server fails
   */
  public void run() {
    // ensure that the server is not started twice
    if (!state.compareAndSet(State.STOPPED, State.RUNNING)) {
      started(true);
      return;
    }

    Selector selector = null;
    ServerSocketChannel server = null;
    try {
      selector = Selector.open();
      server = ServerSocketChannel.open();
      server.socket().bind(new InetSocketAddress(port));
      server.configureBlocking(false);
      server.register(selector, SelectionKey.OP_ACCEPT);
      started(false);
      while (state.get() == State.RUNNING) {
        selector.select(100); // check every 100ms whether the server has been requested to stop
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
          SelectionKey key = it.next();
          try {
            // remove key from the ready list
            it.remove();
            if (key.isConnectable()) {
              ((SocketChannel) key.channel()).finishConnect();
            }
            if (key.isAcceptable()) {
              // accept connection
              SocketChannel client = server.accept();
              client.configureBlocking(false);
              client.socket().setTcpNoDelay(true);
              // channel is registered for further events such as read or write
              SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ);
              connection(acceptKey);
            }
            if (key.isReadable()) {
              for (ByteBuffer message : readIncomingMessage(key)) {
                messageReceived(message, key);
              }
            }
          } catch (IOException ioe) {
            resetKey(key);
            disconnected(key);
          }
        }
      }
    } catch (Throwable e) {
      throw new RuntimeException("Server failure: " + e.getMessage());
    } finally {
      try {
        selector.close();
        server.socket().close();
        server.close();
        state.set(State.STOPPED);
        stopped();
      } catch (Exception e) {
        // do nothing - server failed
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    while (!stop) {
      try {
        selector.select(1000);
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> it = selectedKeys.iterator();
        SelectionKey key = null;
        while (it.hasNext()) {
          key = it.next();
          it.remove();
          try {
            handleInput(key);
          } catch (Exception e) {
            if (key != null) {
              key.cancel();
              if (key.channel() != null) key.channel().close();
            }
          }
        }
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }

    // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭,所以不需要重复释放资源
    if (selector != null)
      try {
        selector.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
  }
示例#13
0
  public static void main(String[] argv) throws Exception {
    Pipe[] pipes = new Pipe[PIPES_COUNT];
    Pipe pipe = Pipe.open();
    Pipe.SinkChannel sink = pipe.sink();
    Pipe.SourceChannel source = pipe.source();
    Selector sel = Selector.open();
    source.configureBlocking(false);
    source.register(sel, SelectionKey.OP_READ);

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i] = Pipe.open();
      Pipe.SourceChannel sc = pipes[i].source();
      sc.configureBlocking(false);
      sc.register(sel, SelectionKey.OP_READ);
      Pipe.SinkChannel sc2 = pipes[i].sink();
      sc2.configureBlocking(false);
      sc2.register(sel, SelectionKey.OP_WRITE);
    }

    for (int i = 0; i < LOOPS; i++) {
      sink.write(ByteBuffer.allocate(BUF_SIZE));
      int x = sel.selectNow();
      sel.selectedKeys().clear();
      source.read(ByteBuffer.allocate(BUF_SIZE));
    }

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i].sink().close();
      pipes[i].source().close();
    }
    pipe.sink().close();
    pipe.source().close();
    sel.close();
  }
 public void testOpenSelector() throws IOException {
   Selector selector = SystemUtils.openSelector();
   assertNotNull(selector);
   assertTrue(selector.isOpen());
   if (SystemUtils.isLinuxPlatform()) {
     final String pollClassName = selector.provider().getClass().getCanonicalName();
     assertTrue(
         pollClassName.equals("sun.nio.ch.EPollSelectorProvider")
             || pollClassName.equals("sun.nio.ch.PollSelectorProvider"));
   }
   Selector selector2 = SystemUtils.openSelector();
   ;
   assertNotSame(selector, selector2);
   selector.close();
   selector2.close();
 }
示例#15
0
    /**
     * The background thread that adds sockets to the Poller, checks the poller for triggered events
     * and hands the associated socket off to an appropriate processor as events occur.
     */
    @Override
    public void run() {
      // Loop until destroy() is called
      while (true) {

        boolean hasEvents = false;

        try {
          if (!close) {
            hasEvents = events();
            if (wakeupCounter.getAndSet(-1) > 0) {
              // if we are here, means we have other stuff to do
              // do a non blocking select
              keyCount = selector.selectNow();
            } else {
              keyCount = selector.select(selectorTimeout);
            }
            wakeupCounter.set(0);
          }
          if (close) {
            events();
            timeout(0, false);
            try {
              selector.close();
            } catch (IOException ioe) {
              log.error(sm.getString("endpoint.nio.selectorCloseFail"), ioe);
            }
            break;
          }
        } catch (Throwable x) {
          ExceptionUtils.handleThrowable(x);
          log.error("", x);
          continue;
        }
        // either we timed out or we woke up, process events first
        if (keyCount == 0) hasEvents = (hasEvents | events());

        Iterator<SelectionKey> iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null;
        // Walk through the collection of ready keys and dispatch
        // any active event.
        while (iterator != null && iterator.hasNext()) {
          SelectionKey sk = iterator.next();
          NioSocketWrapper attachment = (NioSocketWrapper) sk.attachment();
          // Attachment may be null if another thread has called
          // cancelledKey()
          if (attachment == null) {
            iterator.remove();
          } else {
            iterator.remove();
            processKey(sk, attachment);
          }
        } // while

        // process timeouts
        timeout(keyCount, hasEvents);
      } // while

      stopLatch.countDown();
    }
示例#16
0
 /**
  * ������ѯ�ķ�ʽ����selector���Ƿ�����Ҫ������¼�������У�����д���
  *
  * @throws IOException
  */
 public void listen() {
   // ��ѯ����selector
   while (true) {
     int readyChannels = 0;
     try {
       readyChannels = selector.select();
       if (readyChannels == 0) {
         continue;
       }
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       if (selector != null) {
         try {
           selector.close();
         } catch (IOException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
         }
       }
     }
     // ���selector��ѡ�е���ĵ����
     Iterator ite = this.selector.selectedKeys().iterator();
     while (ite.hasNext()) {
       SelectionKey key = (SelectionKey) ite.next();
       // ɾ����ѡ��key,�Է��ظ�����
       ite.remove();
       // �����¼�����
       if (key.isValid() && key.isConnectable()) {
         SocketChannel channel = (SocketChannel) key.channel();
         // ����������ӣ����������
         if (channel.isConnectionPending()) {
           try {
             channel.finishConnect();
             // ���óɷ�����
             channel.configureBlocking(false);
             // ��������Ը����˷�����ϢŶ
             channel.write(ByteBuffer.wrap(new String("�����˷�����һ����Ϣ").getBytes()));
             // �ںͷ�������ӳɹ�֮��Ϊ�˿��Խ��յ�����˵���Ϣ����Ҫ��ͨ�����ö���Ȩ�ޡ�
             channel.register(this.selector, SelectionKey.OP_READ);
           } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             if (channel != null) {
               try {
                 channel.close();
               } catch (IOException e1) {
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
               }
             }
           }
         }
       } else if (key.isReadable()) { // ����˿ɶ����¼�
         read(key);
       }
     }
   }
 }
 /** Shutdown this server, preventing it from handling any more requests. */
 @Override
 public final void stop() {
   try {
     selector.close();
     serverSocketChannel.close();
   } catch (IOException ex) {
   }
 }
  public void close() {
    try {
      _selector.close();

    } catch (IOException e) {
      logger.warning(Util.getErrorMessage(e));
    }
  }
  public void stop() {
    try {
      lock.lock();

      if (networkJob != null && !networkJob.isCancelled()) {
        networkJob.cancel(true);
        networkJob = null;
      }

      try {
        if (selector != null) {

          selector.wakeup();

          boolean isContinue = true;
          while (isContinue) {
            try {
              for (SelectionKey selectionKey : selector.keys()) {
                selectionKey.channel().close();
                selectionKey.cancel();
              }
              isContinue = false; // continue till all keys are cancelled
            } catch (ConcurrentModificationException e) {
              logger.warn(
                  "An exception occurred while closing a selector key : '{}'", e.getMessage());
            }
          }

          selector.close();
        }
      } catch (IOException e) {
        logger.warn("An exception occurred while closing the selector : '{}'", e.getMessage());
      }

      if (broadcastKey != null) {
        try {
          broadcastKey.channel().close();
        } catch (IOException e) {
          logger.warn(
              "An exception occurred while closing the broadcast channel : '{}'", e.getMessage());
        }
      }

      if (unicastKey != null) {
        try {
          unicastKey.channel().close();
        } catch (IOException e) {
          logger.warn(
              "An exception occurred while closing the unicast channel : '{}'", e.getMessage());
        }
      }

      ipAddress = null;
    } finally {
      lock.unlock();
    }
  }
  protected String sendAndReceive(byte[] payload) throws IOException {
    ByteBuffer sbuf = ByteBuffer.wrap(payload);
    ByteBuffer rbuf = ByteBuffer.allocateDirect(256);
    CharsetDecoder rbufDecoder = Charset.forName("UTF-8").newDecoder();
    StringBuilder response = new StringBuilder();

    int ops = SelectionKey.OP_WRITE | SelectionKey.OP_READ;
    if (this.channel.isConnectionPending()) {
      ops = ops | SelectionKey.OP_CONNECT;
    }

    Selector selector = Selector.open();
    try {
      this.channel.register(selector, ops);
      while (true) {
        if (0 < selector.select(Client.POLLS_INTERVAL * 1000)) {
          Iterator keys = selector.selectedKeys().iterator();
          while (keys.hasNext()) {
            SelectionKey key = (SelectionKey) keys.next();
            SocketChannel ch = (SocketChannel) key.channel();
            if (key.isConnectable()) {
              // Just connected
              ch.finishConnect();
            }
            if (key.isReadable() && !sbuf.hasRemaining()) {
              // Receiving the response
              while (0 < ch.read(rbuf)) {
                rbuf.flip();
                response.append(rbufDecoder.decode(rbuf).toString());
              }
              if (2 <= response.length()
                  && response
                      .substring(response.length() - 2, response.length())
                      .equals(SocketClient.TERMINATOR)) {
                response.setLength(response.length() - 2);
                return response.toString();
              } else if (0 == response.length()) {
                throw new IOException("Connection lost");
              }
            }
            if (key.isWritable() && sbuf.hasRemaining()) {
              // Sending the request
              while (0 < ch.write(sbuf) && sbuf.hasRemaining()) {
                //
              }
            }
            keys.remove();
          }
        }
      }
    } catch (java.lang.Exception e) {
      throw new IOException("API communication failed: " + e.toString());
    } finally {
      selector.close();
    }
  }
示例#21
0
 /** Close all connections */
 public void close() throws IOException {
   if (serverChannel != null) {
     serverChannel.close();
     serverChannel.keyFor(selector).cancel();
   }
   clients.clear();
   pendingChanges.clear();
   pendingWriteData.clear();
   selector.close();
 }
示例#22
0
 private void closeSelector() {
   channel.selector = null;
   try {
     selector.close();
   } catch (Exception e) {
     if (logger.isWarnEnabled()) {
       logger.warn("Failed to close a selector.", e);
     }
   }
 }
示例#23
0
 /**
  * Close a resource, logging an error if an error occurs.
  *
  * @param resource the resource to close
  */
 public static void safeClose(final Selector resource) {
   try {
     if (resource != null) {
       closeMsg.closingResource(resource);
       resource.close();
     }
   } catch (ClosedChannelException ignored) {
   } catch (Throwable t) {
     closeMsg.resourceCloseFailed(t, resource);
   }
 }
示例#24
0
 private void handleFatal(WebSocket conn, RuntimeException e) {
   onError(conn, e);
   try {
     selector.close();
   } catch (IOException e1) {
     onError(null, e1);
   }
   for (WebSocketWorker w : decoders) {
     w.interrupt();
   }
 }
示例#25
0
  void register(NioSocketChannel channel, ChannelFuture future) {

    boolean server = !(channel instanceof NioClientSocketChannel);
    Runnable registerTask = new RegisterTask(channel, future, server);
    Selector selector;

    synchronized (startStopLock) {
      if (!started) {
        // Open a selector if this worker didn't start yet.
        try {
          this.selector = selector = Selector.open();
        } catch (Throwable t) {
          throw new ChannelException("Failed to create a selector.", t);
        }

        // Start the worker thread with the new Selector.
        String threadName =
            (server ? "New I/O server worker #" : "New I/O client worker #") + bossId + '-' + id;

        boolean success = false;
        try {
          executor.execute(new IoWorkerRunnable(new ThreadRenamingRunnable(this, threadName)));
          success = true;
        } finally {
          if (!success) {
            // Release the Selector if the execution fails.
            try {
              selector.close();
            } catch (Throwable t) {
              logger.warn("Failed to close a selector.", t);
            }
            this.selector = selector = null;
            // The method will return to the caller at this point.
          }
        }
      } else {
        // Use the existing selector if this worker has been started.
        selector = this.selector;
      }

      assert selector != null && selector.isOpen();

      started = true;
      boolean offered = registerTaskQueue.offer(registerTask);
      assert offered;
    }

    if (wakenUp.compareAndSet(false, true)) {
      selector.wakeup();
    }
  }
示例#26
0
  void register(SctpChannelImpl channel, ChannelFuture future) {

    boolean server = !(channel instanceof SctpClientChannel);
    Runnable registerTask = new RegisterTask(channel, future, server);
    notificationHandler = new SctpNotificationHandler(channel);
    Selector selector;

    synchronized (startStopLock) {
      if (!started) {
        // Open a selector if this worker didn't start yet.
        try {
          this.selector = selector = Selector.open();
        } catch (Throwable t) {
          throw new ChannelException("Failed to create a selector.", t);
        }

        // Start the worker thread with the new Selector.
        boolean success = false;
        try {
          DeadLockProofWorker.start(executor, this);
          success = true;
        } finally {
          if (!success) {
            // Release the Selector if the execution fails.
            try {
              selector.close();
            } catch (Throwable t) {
              if (logger.isWarnEnabled()) {
                logger.warn("Failed to close a selector.", t);
              }
            }
            this.selector = selector = null;
            // The method will return to the caller at this point.
          }
        }
      } else {
        // Use the existing selector if this worker has been started.
        selector = this.selector;
      }

      assert selector != null && selector.isOpen();

      started = true;
      boolean offered = registerTaskQueue.offer(registerTask);
      assert offered;
    }

    if (wakenUp.compareAndSet(false, true)) {
      selector.wakeup();
    }
  }
  private Selector initSelector() throws IOException {
    // Create a new selector
    Selector socketSelector = SelectorProvider.provider().openSelector();

    // Create a new non-blocking server socket channel
    try {
      mServerChannel = ServerSocketChannel.open();
      mServerChannel.configureBlocking(false);

      // Bind the server socket to the specified address and port
      mServerChannel.socket().bind(mAddress);

      // Register the server socket channel, indicating an interest in accepting new connections.
      mServerChannel.register(socketSelector, SelectionKey.OP_ACCEPT);

      return socketSelector;
    } catch (IOException e) {
      // we wan't to throw the original IO issue, not the close issue, so don't throw
      // #close IOException.
      try {
        socketSelector.close();
      } catch (IOException ex) {
        // ignore, we want the other exception
        LOG.warn("Unable to close socket selector", ex);
      }
      throw e;
    } catch (RuntimeException e) {
      // we wan't to throw the original IO issue, not the close issue, so don't throw
      // #close IOException.
      try {
        socketSelector.close();
      } catch (IOException ex) {
        // ignore, we want the other exception
        LOG.warn("Unable to close socket selector", ex);
      }
      throw e;
    }
  }
  /*
   * CancelledKeyException is the failure symptom of 4729342
   * NOTE: The failure is timing dependent and is not always
   * seen immediately when the bug is present.
   */
  public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    isa = new InetSocketAddress(lh, TEST_PORT);
    selector = Selector.open();
    ssc = ServerSocketChannel.open();

    // Create and start a selector in a separate thread.
    new Thread(
            new Runnable() {
              public void run() {
                try {
                  ssc.configureBlocking(false);
                  ssc.socket().bind(isa);
                  sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
                  selector.select();
                } catch (IOException e) {
                  System.err.println("error in selecting thread");
                  e.printStackTrace();
                }
              }
            })
        .start();

    // Wait for above thread to get to select() before we call close.
    Thread.sleep(3000);

    // Try to close. This should wakeup select.
    new Thread(
            new Runnable() {
              public void run() {
                try {
                  SocketChannel sc = SocketChannel.open();
                  sc.connect(isa);
                  ssc.close();
                  sk.cancel();
                  sc.close();
                } catch (IOException e) {
                  System.err.println("error in closing thread");
                  System.err.println(e);
                }
              }
            })
        .start();

    // Wait for select() to be awakened, which should be done by close.
    Thread.sleep(3000);

    selector.wakeup();
    selector.close();
  }
示例#29
0
  /**
   * リソースを例外の発生なしに閉じる。 SelectorはCloseableを実装しないのでオーバーロードで対応。
   *
   * @param resource 閉じるリソース。nullの場合は何もせずに成功扱い。
   * @return 成功したらtrue。何らかのエラーが発生したらfalse。
   */
  public static boolean close(Selector resource) {
    if (resource == null) {
      return true;
    }

    try {
      resource.close();
    } catch (IOException e) {
      Logger.debugWithThread(e);
      return false;
    }

    return true;
  }
示例#30
0
  public void destroy() {

    if (!stopped) {
      try {
        worker.join();
      } catch (InterruptedException e) {
      }

      try {
        selector.close();
      } catch (IOException e) {
      }
    }
  }