Exemplo n.º 1
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();
  }
Exemplo n.º 2
0
 public void run() {
   try {
     sel.close();
   } catch (Throwable th) {
     throw new Error(th);
   }
 }
Exemplo n.º 3
0
 @Test
 public void testCloseAfterConnectCall() throws IOException {
   String connectionId =
       selector.connect(
           new InetSocketAddress("localhost", server.port),
           BUFFER_SIZE,
           BUFFER_SIZE,
           PortType.SSL);
   selector.close(connectionId);
   selector.poll(0);
   Assert.assertTrue(
       "Channel should have been added to disconnected list",
       selector.disconnected().contains(connectionId));
 }
  /*
   * 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();
  }
Exemplo n.º 5
0
 public void run() {
   for (; ; ) {
     try {
       int n = sel.select();
       if (n > 0) processSelectedKeys();
       processPendingTargets();
       if (shutdown) {
         sel.close();
         return;
       }
     } catch (IOException x) {
       x.printStackTrace();
     }
   }
 }
Exemplo n.º 6
0
  void close() {
    try {
      if (mySelector != null) mySelector.close();
    } catch (IOException e) {
    }
    mySelector = null;

    // run down open connections and sockets.
    Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
    while (i.hasNext()) {
      try {
        i.next().close();
      } catch (IOException e) {
      }
    }

    // 29Sep09: We create an ArrayList of the existing connections, then iterate over
    // that to call unbind on them. This is because an unbind can trigger a reconnect,
    // which will add to the Connections HashMap, causing a ConcurrentModificationException.
    // XXX: The correct behavior here would be to latch the various reactor methods to return
    // immediately if the reactor is shutting down.
    ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
    Iterator<EventableChannel> i2 = Connections.values().iterator();
    while (i2.hasNext()) {
      EventableChannel ec = i2.next();
      if (ec != null) {
        conns.add(ec);
      }
    }
    Connections.clear();

    ListIterator<EventableChannel> i3 = conns.listIterator(0);
    while (i3.hasNext()) {
      EventableChannel ec = i3.next();
      eventCallback(ec.getBinding(), EM_CONNECTION_UNBOUND, null);
      ec.close();

      EventableSocketChannel sc = (EventableSocketChannel) ec;
      if (sc != null && sc.isAttached()) DetachedConnections.add(sc);
    }

    ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
    while (i4.hasNext()) {
      EventableSocketChannel ec = i4.next();
      ec.cleanup();
    }
    DetachedConnections.clear();
  }
Exemplo n.º 7
0
 void closeIO() {
   logger.log(Level.FINEST, "Closing server channel, etc.");
   if (serverChannel != null) {
     try {
       serverChannel.close();
     } catch (java.io.IOException ex) {
     }
   }
   serverChannel = null;
   try {
     selector.close();
   } catch (java.io.IOException ex) {
   }
   selector = null;
   logger.log(Level.FINEST, "Closed selector, etc.");
 }
Exemplo n.º 8
0
  /** Close. */
  public void close() {
    if (selector != null) {
      selector.wakeup();
      try {
        selector.close();
      } catch (IOException e1) {
        log.warn("close selector fails", e1);
      } finally {
        selector = null;
      }
    }

    if (connector != null) {
      connector.dispose();
      connector = null;
    }
  }
Exemplo n.º 9
0
  /** Close. */
  public void close() {
    if (selector != null) {
      selector.wakeup();
      try {
        selector.close();
      } catch (IOException e1) {
        log.warn("close selector fails", e1);
      } finally {
        selector = null;
      }
    }

    if (server != null) {
      try {
        server.socket().close();
        server.close();
      } catch (IOException e) {
        log.warn("close socket server fails", e);
      } finally {
        server = null;
      }
    }
  }
Exemplo n.º 10
0
 @After
 public void teardown() throws Exception {
   selector.close();
   server.close();
 }
Exemplo n.º 11
0
  /**
   * Operates in a loop, accepting new connections and ensuring that requests on those connections
   * are handled properly.
   */
  @Override
  public void run() {
    setName(handlerName);
    boolean listening = false;
    boolean starting = true;

    while (!shutdownRequested) {
      // If this connection handler is not enabled, then just sleep
      // for a bit and check again.
      if (!enabled) {
        if (listening) {
          cleanUpSelector();
          listening = false;

          logger.info(NOTE_CONNHANDLER_STOPPED_LISTENING, handlerName);
        }

        if (starting) {
          // This may happen if there was an initialisation error
          // which led to disable the connector.
          // The main thread is waiting for the connector to listen
          // on its port, which will not occur yet,
          // so notify here to allow the server startup to complete.
          synchronized (waitListen) {
            starting = false;
            waitListen.notify();
          }
        }

        StaticUtils.sleep(1000);
        continue;
      }

      // If we have gotten here, then we are about to start listening
      // for the first time since startup or since we were previously
      // disabled. Make sure to start with a clean selector and then
      // create all the listeners.
      try {
        cleanUpSelector();

        int numRegistered = registerChannels();

        // At this point, the connection Handler either started
        // correctly or failed to start but the start process
        // should be notified and resume its work in any cases.
        synchronized (waitListen) {
          waitListen.notify();
        }

        // If none of the listeners were created successfully, then
        // consider the connection handler disabled and require
        // administrative action before trying again.
        if (numRegistered == 0) {
          logger.error(ERR_LDAP_CONNHANDLER_NO_ACCEPTORS, currentConfig.dn());

          enabled = false;
          continue;
        }

        listening = true;

        // Enter a loop, waiting for new connections to arrive and
        // then accepting them as they come in.
        boolean lastIterationFailed = false;
        while (enabled && !shutdownRequested) {
          try {
            serveIncomingConnections();

            lastIterationFailed = false;
          } catch (Exception e) {
            logger.traceException(e);
            logger.error(
                ERR_CONNHANDLER_CANNOT_ACCEPT_CONNECTION,
                friendlyName,
                currentConfig.dn(),
                getExceptionMessage(e));

            if (lastIterationFailed) {
              // The last time through the accept loop we also
              // encountered a failure. Rather than enter a potential
              // infinite loop of failures, disable this acceptor and
              // log an error.
              LocalizableMessage message =
                  ERR_CONNHANDLER_CONSECUTIVE_ACCEPT_FAILURES.get(
                      friendlyName, currentConfig.dn(), stackTraceToSingleLineString(e));
              logger.error(message);

              DirectoryServer.sendAlertNotification(
                  this, ALERT_TYPE_LDAP_CONNECTION_HANDLER_CONSECUTIVE_FAILURES, message);

              cleanUpSelector();
              enabled = false;
            } else {
              lastIterationFailed = true;
            }
          }
        }

        if (shutdownRequested) {
          cleanUpSelector();
          selector.close();
          listening = false;
          enabled = false;
        }

      } catch (Exception e) {
        logger.traceException(e);

        // This is very bad because we failed outside the loop. The
        // only thing we can do here is log a message, send an alert,
        // and disable the selector until an administrator can figure
        // out what's going on.
        LocalizableMessage message =
            ERR_LDAP_CONNHANDLER_UNCAUGHT_ERROR.get(
                currentConfig.dn(), stackTraceToSingleLineString(e));
        logger.error(message);

        DirectoryServer.sendAlertNotification(
            this, ALERT_TYPE_LDAP_CONNECTION_HANDLER_UNCAUGHT_ERROR, message);

        cleanUpSelector();
        enabled = false;
      }
    }
  }