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

The following examples show how to use java.nio.channels.Selector#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: WakeupSpeed.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String argv[]) throws Exception {
    int waitTime = 4000;
    Selector selector = Selector.open();
    try {
        selector.wakeup();

        long t1 = System.currentTimeMillis();
        selector.select(waitTime);
        long t2 = System.currentTimeMillis();
        long totalTime = t2 - t1;

        if (totalTime > waitTime)
            throw new RuntimeException("Test failed");
    } finally {
        selector.close();
    }
}
 
Example 2
Source File: WakeupAfterClose.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Selector sel = Selector.open();

    Runnable r = new Runnable() {
        public void run() {
            try {
                sel.select();
            } catch (IOException x) {
                x.printStackTrace();
            }
        }
    };

    // start thread to block in Selector
    Thread t = new Thread(r);
    t.start();

    // give thread time to start
    Thread.sleep(1000);

    // interrupt, close, and wakeup is the magic sequence to provoke the NPE
    t.interrupt();
    sel.close();
    sel.wakeup();
}
 
Example 3
Source File: WakeupAfterClose.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Selector sel = Selector.open();

    Runnable r = new Runnable() {
        public void run() {
            try {
                sel.select();
            } catch (IOException x) {
                x.printStackTrace();
            }
        }
    };

    // start thread to block in Selector
    Thread t = new Thread(r);
    t.start();

    // give thread time to start
    Thread.sleep(1000);

    // interrupt, close, and wakeup is the magic sequence to provoke the NPE
    t.interrupt();
    sel.close();
    sel.wakeup();
}
 
Example 4
Source File: IOUtils.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void closeHard(final Selector selector) {

      try {

         // Close channels
         for (final SelectionKey key : selector.keys()) {

            // Close the channel
            closeHard(key.channel());
         }

         // Close the selector
         selector.selectNow();
         selector.close();
      } catch (final Exception e) {
         ignoreException(e, "closing hard");
      }
   }
 
Example 5
Source File: NioSelectorPool.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void close() throws IOException {
    enabled = false;
    Selector s;
    while ( (s = selectors.poll()) != null ) s.close();
    spare.set(0);
    active.set(0);
    if (blockingSelector!=null) {
        blockingSelector.close();
    }
    if ( SHARED && getSharedSelector()!=null ) {
        getSharedSelector().close();
        SHARED_SELECTOR = null;
    }
}
 
Example 6
Source File: NioSelectorPool.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public void put(Selector s) throws IOException {
    if ( SHARED ) return;
    if ( enabled ) active.decrementAndGet();
    if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) {
        spare.incrementAndGet();
        selectors.offer(s);
    }
    else s.close();
}
 
Example 7
Source File: NioSelectorPool.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void put(Selector s) throws IOException {
    if ( SHARED ) return;
    if ( enabled ) active.decrementAndGet();
    if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) {
        spare.incrementAndGet();
        selectors.offer(s);
    }
    else s.close();
}
 
Example 8
Source File: NioSelectorPool.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public void put(Selector s) throws IOException {
    if ( SHARED ) return;
    if ( enabled ) active.decrementAndGet();
    if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) {
        spare.incrementAndGet();
        selectors.offer(s);
    }
    else s.close();
}
 
Example 9
Source File: TestMessageIO.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Waits for up to 1 second for the server to be acceptable */
private static void awaitAcceptable(ServerSocketChannel channel) throws IOException {
    Selector selector = Selector.open();
    SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
    try {
        assertEquals(true, awaitOp(selector, key, SelectionKey.OP_ACCEPT));
    } finally {
        // Cancel key and close selector
        key.cancel();
        selector.close();
    }
}
 
Example 10
Source File: SelectTimeout.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static boolean test(final long timeout)
    throws InterruptedException, IOException {
    AtomicReference<Exception> theException =
        new AtomicReference<>();
    AtomicBoolean isTimedOut = new AtomicBoolean();

    Selector selector = Selector.open();

    Thread t = new Thread(() -> {
        try {
            selector.select(timeout);
            isTimedOut.set(true);
        } catch (IOException ioe) {
            theException.set(ioe);
        }
    });
    t.start();

    t.join(SLEEP_MILLIS);

    boolean result;
    if (theException.get() == null) {
        if (timeout > SLEEP_MILLIS && isTimedOut.get()) {
            System.err.printf("Test timed out early with timeout %d%n",
                timeout);
            result = false;
        } else {
            System.out.printf("Test succeeded with timeout %d%n", timeout);
            result = true;
        }
    } else {
        System.err.printf("Test failed with timeout %d%n", timeout);
        theException.get().printStackTrace();
        result = false;
    }

    t.interrupt();
    selector.close();

    return result;
}
 
Example 11
Source File: RacyDeregister.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 12
Source File: RacyDeregister.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 13
Source File: RacyDeregister.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 14
Source File: RacyDeregister.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 15
Source File: IOUtils.java    From jsongood with Apache License 2.0 3 votes vote down vote up
/**
 * Unconditionally close a <code>Selector</code>.
 * <p>
 * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *       
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(Selector selector){
    if (selector != null){
        try {
          selector.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}
 
Example 16
Source File: IOUtils.java    From apkeditor with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Closes a <code>Selector</code> unconditionally.
 * <p/>
 * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(final Selector selector) {
    if (selector != null) {
        try {
            selector.close();
        } catch (final IOException ioe) {
            // ignored
        }
    }
}
 
Example 17
Source File: IOUtils.java    From Android-RTEditor with Apache License 2.0 3 votes vote down vote up
/**
 * Unconditionally close a <code>Selector</code>.
 * <p/>
 * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(Selector selector) {
    if (selector != null) {
        try {
            selector.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}
 
Example 18
Source File: IOUtils.java    From AndroidBase with Apache License 2.0 3 votes vote down vote up
/**
 * Unconditionally close a <code>Selector</code>.
 * <p/>
 * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(Selector selector) {
    if (selector != null) {
        try {
            selector.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}
 
Example 19
Source File: IOUtils.java    From android-common with Apache License 2.0 3 votes vote down vote up
/**
 * Unconditionally close a <code>Selector</code>.
 * <p/>
 * Equivalent to {@link java.nio.channels.Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(Selector selector) {
    if (selector != null) {
        try {
            selector.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}
 
Example 20
Source File: IOUtils.java    From typescript.java with MIT License 3 votes vote down vote up
/**
 * Unconditionally close a <code>Selector</code>.
 * <p>
 * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p>
 * Example code:
 * <pre>
 *   Selector selector = null;
 *   try {
 *       selector = Selector.open();
 *       // process socket
 *       
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(selector);
 *   }
 * </pre>
 *
 * @param selector the Selector to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(Selector selector){
    if (selector != null){
        try {
          selector.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}