下面列出了java.nio.channels.Selector#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
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();
}
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");
}
}
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();
}
}
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();
}
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;
}
}
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();
}
/** 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();
}
}
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();
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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;
}
/**
* 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
}
}
}
/**
* 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
}
}
}
/**
* 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
}
}
}
/**
* 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
}
}
}
/**
* 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
}
}
}
/**
* 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
}
}
}