public static void shutdown() {
    logger_.info("Shutting down ...");
    synchronized (MessagingService.class) {
      /* Stop listening on any socket */
      for (SelectionKey skey : listenSockets_.values()) {
        SelectorManager.getSelectorManager().cancel(skey);
      }
      listenSockets_.clear();

      /* Shutdown the threads in the EventQueue's */
      messageDeserializationExecutor_.shutdownNow();
      messageSerializerExecutor_.shutdownNow();
      messageDeserializerExecutor_.shutdownNow();
      streamExecutor_.shutdownNow();

      /* shut down the cachetables */
      taskCompletionMap_.shutdown();
      callbackMap_.shutdown();

      /* Interrupt the selector manager thread */
      SelectorManager.getSelectorManager().interrupt();

      poolTable_.clear();
      verbHandlers_.clear();
      bShutdown_ = true;
    }
    logger_.debug("Shutdown invocation complete.");
  }
Beispiel #2
0
  @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);
        }
      }
    }
  }
  @Test
  public void testWriteBlocked() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(10000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    // Write client to server
    _writeCount = 10000;
    String data = "Now is the time for all good men to come to the aid of the party";
    client.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
    BufferedInputStream in = new BufferedInputStream(client.getInputStream());

    int byteNum = 0;
    try {
      for (int i = 0; i < _writeCount; i++) {
        if (i % 1000 == 0) TimeUnit.MILLISECONDS.sleep(200);

        // Verify echo server to client
        for (int j = 0; j < data.length(); j++) {
          char c = data.charAt(j);
          int b = in.read();
          byteNum++;
          assertTrue(b > 0);
          assertEquals("test-" + i + "/" + j, c, (char) b);
        }

        if (i == 0) _lastEndPoint.setIdleTimeout(60000);
      }
    } catch (SocketTimeoutException e) {
      System.err.println("SelectorManager.dump() = " + _manager.dump());
      LOG.warn("Server: " + server);
      LOG.warn("Error reading byte #" + byteNum, e);
      throw e;
    }

    client.close();

    for (int i = 0; i < 10; ++i) {
      if (server.isOpen()) Thread.sleep(10);
      else break;
    }
    assertFalse(server.isOpen());
  }
 @Before
 public void startManager() throws Exception {
   _connector = ServerSocketChannel.open();
   _connector.socket().bind(null);
   _threadPool.start();
   _manager.start();
 }
 @After
 public void destroy() throws Exception {
   if (scheduler != null) scheduler.stop();
   if (selectorManager != null) selectorManager.stop();
   if (connector != null) connector.close();
   if (threadPool != null) threadPool.stop();
 }
 @After
 public void stopManager() throws Exception {
   _scheduler.stop();
   _manager.stop();
   _threadPool.stop();
   _connector.close();
 }
  @Test
  public void testBlockedReadIdle() throws Exception {
    Socket client = newClient();
    InputStream clientInputStream = client.getInputStream();
    OutputStream clientOutputStream = client.getOutputStream();

    client.setSoTimeout(5000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    // Write client to server
    clientOutputStream.write("HelloWorld".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = clientInputStream.read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    int idleTimeout = 500;
    _lastEndPoint.setIdleTimeout(idleTimeout);

    // Write 8 and cause block waiting for 10
    _blockAt = 10;
    clientOutputStream.write("12345678".getBytes(StandardCharsets.UTF_8));
    clientOutputStream.flush();

    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = clientInputStream.read();
    assertEquals('E', b);
    long idle = System.currentTimeMillis() - start;
    assertTrue(idle > idleTimeout / 2);
    assertTrue(idle < idleTimeout * 2);

    for (char c : "E: 12345678".toCharArray()) {
      b = clientInputStream.read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }
    b = clientInputStream.read();
    assertEquals(-1, b);

    // But endpoint is still open.
    if (_lastEndPoint.isOpen())
      // Wait for another idle callback
      Thread.sleep(idleTimeout * 2);

    // endpoint is closed.
    assertFalse(_lastEndPoint.isOpen());
  }
Beispiel #8
0
 Reactor(SelectorManager selectorManager, Configuration configuration, int index)
     throws IOException {
   super();
   reactorIndex = index;
   this.selectorManager = selectorManager;
   controller = selectorManager.getController();
   selector = SystemUtils.openSelector();
   this.configuration = configuration;
   setName("HS4J-Reactor-" + index);
 }
 @Before
 public void startManager() throws Exception {
   _writeCount = 1;
   _lastEndPoint = null;
   _lastEndPointLatch = new CountDownLatch(1);
   _connector = ServerSocketChannel.open();
   _connector.socket().bind(null);
   _scheduler.start();
   _threadPool.start();
   _manager.start();
 }
  @Test
  public void testEcho() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(60000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // wait for read timeout
    client.setSoTimeout(500);
    long start = System.currentTimeMillis();
    try {
      client.getInputStream().read();
      Assert.fail();
    } catch (SocketTimeoutException e) {
      long duration = System.currentTimeMillis() - start;
      Assert.assertThat("timeout duration", duration, greaterThanOrEqualTo(400L));
    }

    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
      int b = client.getInputStream().read();
      Assert.assertThat("expect valid char integer", b, greaterThan(0));
      assertEquals("expect characters to be same", c, (char) b);
    }
    client.close();

    for (int i = 0; i < 10; ++i) {
      if (server.isOpen()) Thread.sleep(10);
      else break;
    }
    assertFalse(server.isOpen());
  }
  public void init(final Interested interested) throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.start();

    scheduler = new TimerScheduler();
    scheduler.start();

    connector = ServerSocketChannel.open();
    connector.bind(new InetSocketAddress("localhost", 0));

    selectorManager =
        new SelectorManager(threadPool, scheduler) {

          @Override
          protected EndPoint newEndPoint(
              SelectableChannel channel, ManagedSelector selector, SelectionKey key)
              throws IOException {
            SocketChannelEndPoint endp =
                new SocketChannelEndPoint(channel, selector, key, getScheduler()) {
                  @Override
                  protected void onIncompleteFlush() {
                    super.onIncompleteFlush();
                    interested.onIncompleteFlush();
                  }
                };

            endp.setIdleTimeout(60000);
            return endp;
          }

          @Override
          public Connection newConnection(
              SelectableChannel channel, final EndPoint endPoint, Object attachment) {
            return new AbstractConnection(endPoint, getExecutor()) {
              @Override
              public void onOpen() {
                super.onOpen();
                fillInterested();
              }

              @Override
              public void onFillable() {
                interested.onFillable(endPoint, this);
              }
            };
          }
        };
    selectorManager.start();
  }
  @Test
  public void testStress() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(30000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.register(server);
    int writes = 100000;

    final byte[] bytes = "HelloWorld".getBytes("UTF-8");
    final CountDownLatch latch = new CountDownLatch(writes);
    final InputStream in = new BufferedInputStream(client.getInputStream());
    final long start = System.currentTimeMillis();
    client.getOutputStream().write(bytes);
    client.getOutputStream().flush();

    new Thread() {
      public void run() {
        try {
          while (latch.getCount() > 0) {
            // Verify echo server to client
            for (byte b0 : bytes) {
              int b = in.read();
              assertTrue(b > 0);
              assertEquals(0xff & b0, b);
            }
            latch.countDown();
          }
        } catch (Throwable e) {
          System.err.println("latch=" + latch.getCount());
          System.err.println("time=" + (System.currentTimeMillis() - start));
          e.printStackTrace();
        }
      }
    }.start();

    // Write client to server
    for (int i = 1; i < writes; i++) {
      client.getOutputStream().write(bytes);
      Thread.yield();
    }
    client.getOutputStream().flush();

    assertTrue(latch.await(100, TimeUnit.SECONDS));
  }
  @Test
  public void testBlockIn() throws Exception {
    Socket client = newClient();

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.register(server);

    OutputStream clientOutputStream = client.getOutputStream();
    InputStream clientInputStream = client.getInputStream();

    int specifiedTimeout = 400;
    client.setSoTimeout(specifiedTimeout);

    // Write 8 and cause block for 10
    _blockAt = 10;
    clientOutputStream.write("12345678".getBytes("UTF-8"));
    clientOutputStream.flush();

    Thread.sleep(2 * specifiedTimeout);

    // No echo as blocking for 10
    long start = System.currentTimeMillis();
    try {
      int b = clientInputStream.read();
      Assert.fail("Should have timed out waiting for a response, but read " + b);
    } catch (SocketTimeoutException e) {
      int elapsed = Long.valueOf(System.currentTimeMillis() - start).intValue();
      System.err.println("blocked for " + elapsed + "ms");
      Assert.assertThat(
          "Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4));
    }

    // write remaining characters
    clientOutputStream.write("90ABCDEF".getBytes("UTF-8"));
    clientOutputStream.flush();

    // Verify echo server to client
    for (char c : "1234567890ABCDEF".toCharArray()) {
      int b = clientInputStream.read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }
  }
  @Test
  public void testReadBlocked() throws Exception {
    Socket client = newClient();

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    OutputStream clientOutputStream = client.getOutputStream();
    InputStream clientInputStream = client.getInputStream();

    int specifiedTimeout = 1000;
    client.setSoTimeout(specifiedTimeout);

    // Write 8 and cause block waiting for 10
    _blockAt = 10;
    clientOutputStream.write("12345678".getBytes(StandardCharsets.UTF_8));
    clientOutputStream.flush();

    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    _lastEndPoint.setIdleTimeout(10 * specifiedTimeout);
    Thread.sleep((11 * specifiedTimeout) / 10);

    long start = System.currentTimeMillis();
    try {
      int b = clientInputStream.read();
      Assert.fail("Should have timed out waiting for a response, but read " + b);
    } catch (SocketTimeoutException e) {
      int elapsed = Long.valueOf(System.currentTimeMillis() - start).intValue();
      Assert.assertThat(
          "Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4));
    }

    // write remaining characters
    clientOutputStream.write("90ABCDEF".getBytes(StandardCharsets.UTF_8));
    clientOutputStream.flush();

    // Verify echo server to client
    for (char c : "1234567890ABCDEF".toCharArray()) {
      int b = clientInputStream.read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }
  }
  @Test
  public void testShutdown() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(500);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.register(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes("UTF-8"));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // wait for read timeout
    long start = System.currentTimeMillis();
    try {
      client.getInputStream().read();
      Assert.fail();
    } catch (SocketTimeoutException e) {
      assertTrue(System.currentTimeMillis() - start >= 400);
    }

    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes("UTF-8"));
    client.shutdownOutput();

    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // Read close
    assertEquals(-1, client.getInputStream().read());
  }
  public void listen(EndPoint localEp, boolean isHttp) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    ServerSocket ss = serverChannel.socket();
    ss.bind(localEp.getInetAddress());
    serverChannel.configureBlocking(false);

    SelectionKeyHandler handler = null;
    if (isHttp) {
      handler = new HttpConnectionHandler();
    } else {
      handler = new TcpConnectionHandler(localEp);
    }

    SelectionKey key =
        SelectorManager.getSelectorManager()
            .register(serverChannel, handler, SelectionKey.OP_ACCEPT);
    endPoints_.add(localEp);
    listenSockets_.put(localEp, key);
  }
  @Test
  public void testIdle() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(3000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.register(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes("UTF-8"));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // Set Max idle
    _lastEndp.setMaxIdleTime(500);

    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = client.getInputStream().read();
    assertEquals(-1, b);
    long idle = System.currentTimeMillis() - start;
    assertThat(idle, Matchers.greaterThan(400L));
    assertThat(idle, Matchers.lessThan(3000L));

    if (_lastEndp.isOpen()) {
      // half close so wait another idle period
      assertTrue(_lastEndp.isOutputShutdown());
      Thread.sleep(2000);
    }

    // endpoint is closed.
    assertFalse(_lastEndp.isOpen());
  }
  @Test
  public void testIdle() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(3000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    int idleTimeout = 500;
    _lastEndPoint.setIdleTimeout(idleTimeout);

    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = client.getInputStream().read();
    assertEquals(-1, b);
    long idle = System.currentTimeMillis() - start;
    assertTrue(idle > idleTimeout / 2);
    assertTrue(idle < idleTimeout * 2);

    // But endpoint may still be open for a little bit.
    for (int i = 0; i < 10; ++i) {
      if (_lastEndPoint.isOpen()) Thread.sleep(2 * idleTimeout / 10);
      else break;
    }
    assertFalse(_lastEndPoint.isOpen());
  }
Beispiel #19
0
 public void halt() {
   impl.halt();
 }
  @Test
  public void testReadBlockedThenWriteBlockedThenReadableThenWritable() throws Exception {
    final AtomicInteger size = new AtomicInteger(1024 * 1024);
    final AtomicReference<Exception> failure = new AtomicReference<>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final AtomicBoolean writeBlocked = new AtomicBoolean();
    init(
        new Interested() {
          @Override
          public void onFillable(EndPoint endPoint, AbstractConnection connection) {
            ByteBuffer input = BufferUtil.allocate(2);
            int read = fill(endPoint, input);

            if (read == 1) {
              byte b = input.get();
              if (b == 1) {
                connection.fillInterested();

                ByteBuffer output = ByteBuffer.allocate(size.get());
                endPoint.write(new Callback() {}, output);

                latch1.countDown();
              } else {
                latch2.countDown();
              }
            } else {
              failure.set(new Exception("Unexpectedly read " + read + " bytes"));
            }
          }

          @Override
          public void onIncompleteFlush() {
            writeBlocked.set(true);
          }

          private int fill(EndPoint endPoint, ByteBuffer buffer) {
            try {
              return endPoint.fill(buffer);
            } catch (IOException x) {
              failure.set(x);
              return 0;
            }
          }
        });

    Socket client = new Socket();
    client.connect(connector.getLocalAddress());
    client.setSoTimeout(5000);

    SocketChannel server = connector.accept();
    server.configureBlocking(false);
    selectorManager.accept(server);

    OutputStream clientOutput = client.getOutputStream();
    clientOutput.write(1);
    clientOutput.flush();
    Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));

    // We do not read to keep the socket write blocked

    clientOutput.write(2);
    clientOutput.flush();
    Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));

    // Sleep before reading to allow waking up the server only for read
    Thread.sleep(1000);

    // Now read what was written, waking up the server for write
    InputStream clientInput = client.getInputStream();
    while (size.getAndDecrement() > 0) clientInput.read();

    client.close();

    Assert.assertNull(failure.get());
  }
  @Slow
  @Test
  public void testConnectTimeoutBeforeSuccessfulConnect() throws Exception {
    ServerSocketChannel server = ServerSocketChannel.open();
    server.bind(new InetSocketAddress("localhost", 0));
    SocketAddress address = server.getLocalAddress();

    final AtomicLong timeoutConnection = new AtomicLong();
    final long connectTimeout = 1000;
    SelectorManager selectorManager =
        new SelectorManager(executor, scheduler) {
          @Override
          protected EndPoint newEndPoint(
              SocketChannel channel, ManagedSelector selector, SelectionKey selectionKey)
              throws IOException {
            return new SelectChannelEndPoint(
                channel, selector, selectionKey, getScheduler(), connectTimeout / 2);
          }

          @Override
          protected boolean finishConnect(SocketChannel channel) throws IOException {
            try {
              long timeout = timeoutConnection.get();
              if (timeout > 0) TimeUnit.MILLISECONDS.sleep(timeout);
              return super.finishConnect(channel);
            } catch (InterruptedException e) {
              return false;
            }
          }

          @Override
          public Connection newConnection(
              SocketChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            ((Callback) attachment).succeeded();
            return new AbstractConnection(endpoint, executor) {
              @Override
              public void onFillable() {}
            };
          }

          @Override
          protected void connectionFailed(SocketChannel channel, Throwable ex, Object attachment) {
            ((Callback) attachment).failed(ex);
          }
        };
    selectorManager.setConnectTimeout(connectTimeout);
    selectorManager.start();

    try {
      SocketChannel client1 = SocketChannel.open();
      client1.configureBlocking(false);
      client1.connect(address);
      long timeout = connectTimeout * 2;
      timeoutConnection.set(timeout);
      final CountDownLatch latch1 = new CountDownLatch(1);
      selectorManager.connect(
          client1,
          new Callback.Adapter() {
            @Override
            public void failed(Throwable x) {
              latch1.countDown();
            }
          });
      Assert.assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS));
      Assert.assertFalse(client1.isOpen());

      // Wait for the first connect to finish, as the selector thread is waiting in finishConnect().
      Thread.sleep(timeout);

      // Verify that after the failure we can connect successfully.
      try (SocketChannel client2 = SocketChannel.open()) {
        client2.configureBlocking(false);
        client2.connect(address);
        timeoutConnection.set(0);
        final CountDownLatch latch2 = new CountDownLatch(1);
        selectorManager.connect(
            client2,
            new Callback.Adapter() {
              @Override
              public void succeeded() {
                latch2.countDown();
              }
            });
        Assert.assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS));
        Assert.assertTrue(client2.isOpen());
      }
    } finally {
      selectorManager.stop();
    }
  }
  @Test
  public void testStress() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(30000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);
    final int writes = 200000;

    final byte[] bytes = "HelloWorld-".getBytes(StandardCharsets.UTF_8);
    byte[] count = "0\n".getBytes(StandardCharsets.UTF_8);
    BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
    final CountDownLatch latch = new CountDownLatch(writes);
    final InputStream in = new BufferedInputStream(client.getInputStream());
    final long start = System.currentTimeMillis();
    out.write(bytes);
    out.write(count);
    out.flush();

    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    _lastEndPoint.setIdleTimeout(5000);

    new Thread() {
      @Override
      public void run() {
        Thread.currentThread().setPriority(MAX_PRIORITY);
        long last = -1;
        int count = -1;
        try {
          while (latch.getCount() > 0) {
            // Verify echo server to client
            for (byte b0 : bytes) {
              int b = in.read();
              Assert.assertThat(b, greaterThan(0));
              assertEquals(0xff & b0, b);
            }

            count = 0;
            int b = in.read();
            while (b > 0 && b != '\n') {
              count = count * 10 + (b - '0');
              b = in.read();
            }
            last = System.currentTimeMillis();

            // if (latch.getCount()%1000==0)
            //    System.out.println(writes-latch.getCount());

            latch.countDown();
          }
        } catch (Throwable e) {

          long now = System.currentTimeMillis();
          System.err.println("count=" + count);
          System.err.println("latch=" + latch.getCount());
          System.err.println("time=" + (now - start));
          System.err.println("last=" + (now - last));
          System.err.println("endp=" + _lastEndPoint);
          System.err.println("conn=" + _lastEndPoint.getConnection());

          e.printStackTrace();
        }
      }
    }.start();

    // Write client to server
    for (int i = 1; i < writes; i++) {
      out.write(bytes);
      out.write(Integer.toString(i).getBytes(StandardCharsets.ISO_8859_1));
      out.write('\n');
      if (i % 1000 == 0) {
        // System.err.println(i+"/"+writes);
        out.flush();
      }
      Thread.yield();
    }
    out.flush();

    long last = latch.getCount();
    while (!latch.await(5, TimeUnit.SECONDS)) {
      // System.err.println(latch.getCount());
      if (latch.getCount() == last) Assert.fail();
      last = latch.getCount();
    }

    assertEquals(0, latch.getCount());
  }
  // TODO make this test reliable
  @Test
  @Ignore
  public void testRejectedExecution() throws Exception {
    _manager.stop();
    _threadPool.stop();

    final CountDownLatch latch = new CountDownLatch(1);

    BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(4);
    _threadPool = new QueuedThreadPool(4, 4, 60000, q);
    _manager =
        new SelectorManager(_threadPool, _scheduler, 1) {

          @Override
          protected EndPoint newEndPoint(
              SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey)
              throws IOException {
            SocketChannelEndPoint endp =
                new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
            _lastEndPoint = endp;
            _lastEndPointLatch.countDown();
            return endp;
          }

          @Override
          public Connection newConnection(
              SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            return new TestConnection(endpoint, latch);
          }
        };

    _threadPool.start();
    _manager.start();

    AtomicInteger timeout = new AtomicInteger();
    AtomicInteger rejections = new AtomicInteger();
    AtomicInteger echoed = new AtomicInteger();

    CountDownLatch closed = new CountDownLatch(20);
    for (int i = 0; i < 20; i++) {
      new Thread() {
        public void run() {
          try (Socket client = newClient(); ) {
            client.setSoTimeout(5000);

            SocketChannel server = _connector.accept();
            server.configureBlocking(false);

            _manager.accept(server);

            // Write client to server
            client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
            client.getOutputStream().flush();
            client.shutdownOutput();

            // Verify echo server to client
            for (char c : "HelloWorld".toCharArray()) {
              int b = client.getInputStream().read();
              assertTrue(b > 0);
              assertEquals(c, (char) b);
            }
            assertEquals(-1, client.getInputStream().read());
            echoed.incrementAndGet();
          } catch (SocketTimeoutException x) {
            x.printStackTrace();
            timeout.incrementAndGet();
          } catch (Throwable x) {
            rejections.incrementAndGet();
          } finally {
            closed.countDown();
          }
        }
      }.start();
    }

    // unblock the handling
    latch.countDown();

    // wait for all clients to complete or fail
    closed.await();

    // assert some clients must have been rejected
    Assert.assertThat(rejections.get(), Matchers.greaterThan(0));
    // but not all of them
    Assert.assertThat(rejections.get(), Matchers.lessThan(20));
    // none should have timed out
    Assert.assertThat(timeout.get(), Matchers.equalTo(0));
    // and the rest should have worked
    Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get()));

    // and the selector is still working for new requests
    try (Socket client = newClient(); ) {
      client.setSoTimeout(5000);

      SocketChannel server = _connector.accept();
      server.configureBlocking(false);

      _manager.accept(server);

      // Write client to server
      client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
      client.getOutputStream().flush();
      client.shutdownOutput();

      // Verify echo server to client
      for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
      }
      assertEquals(-1, client.getInputStream().read());
    }
  }
Beispiel #24
0
 public void add(TimerQueueAction a) {
   impl.add(a);
 }
Beispiel #25
0
 public void remove(TimerQueueAction a) {
   impl.remove(a);
 }
Beispiel #26
0
 public int depth() {
   return impl.poolSize(SelectorRequest.Type.TIMER);
 }