OnJava8-Examples/threads/NIOInterruption.java

60 lines
1.9 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/NIOInterruption.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Interrupting a blocked NIO channel
2015-06-15 17:47:35 -07:00
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.concurrent.*;
import java.io.*;
class NIOBlocked implements Runnable {
private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) { this.sc = sc; }
@Override
public void run() {
try {
2015-11-03 12:00:44 -08:00
System.out.println("Waiting for read() in " + this);
2015-06-15 17:47:35 -07:00
sc.read(ByteBuffer.allocate(1));
} catch(ClosedByInterruptException e) {
2015-11-03 12:00:44 -08:00
System.out.println("ClosedByInterruptException");
2015-06-15 17:47:35 -07:00
} catch(AsynchronousCloseException e) {
2015-11-03 12:00:44 -08:00
System.out.println("AsynchronousCloseException");
2015-06-15 17:47:35 -07:00
} catch(IOException e) {
throw new RuntimeException(e);
}
2016-01-25 18:05:55 -08:00
System.out.println(
"Exiting NIOBlocked.run() " + this);
2015-06-15 17:47:35 -07:00
}
}
public class NIOInterruption {
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
ExecutorService es = Executors.newCachedThreadPool();
2015-06-15 17:47:35 -07:00
InetSocketAddress isa =
new InetSocketAddress("localhost", 8080);
2015-12-15 11:47:04 -08:00
try(ServerSocket server = new ServerSocket(8080);
SocketChannel sc1 = SocketChannel.open(isa);
SocketChannel sc2 = SocketChannel.open(isa)) {
2016-01-25 18:05:55 -08:00
Future<?> f = es.submit(new NIOBlocked(sc1));
es.execute(new NIOBlocked(sc2));
es.shutdown();
2015-06-15 17:47:35 -07:00
TimeUnit.SECONDS.sleep(1);
// Produce an interrupt via cancel:
f.cancel(true);
TimeUnit.SECONDS.sleep(1);
// Release the block by closing the channel:
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-12-15 11:47:04 -08:00
Waiting for read() in NIOBlocked@122af49
Waiting for read() in NIOBlocked@1feeb4a
2015-06-15 17:47:35 -07:00
ClosedByInterruptException
2015-12-15 11:47:04 -08:00
Exiting NIOBlocked.run() NIOBlocked@122af49
2015-06-15 17:47:35 -07:00
AsynchronousCloseException
2015-12-15 11:47:04 -08:00
Exiting NIOBlocked.run() NIOBlocked@1feeb4a
2015-09-07 11:44:36 -06:00
*/