OnJava8-Examples/concurrency/NIOInterruption.java

55 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// concurrency/NIOInterruption.java
2015-06-15 17:47:35 -07:00
// Interrupting a blocked NIO channel.
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);
}
2015-11-03 12:00:44 -08:00
System.out.println("Exiting NIOBlocked.run() " + this);
2015-06-15 17:47:35 -07:00
}
}
public class NIOInterruption {
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InetSocketAddress isa =
new InetSocketAddress("localhost", 8080);
SocketChannel sc1 = SocketChannel.open(isa);
try(SocketChannel sc2 = SocketChannel.open(isa)) {
Future<?> f = exec.submit(new NIOBlocked(sc1));
exec.execute(new NIOBlocked(sc2));
exec.shutdown();
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-06-15 17:47:35 -07:00
Waiting for read() in NIOBlocked@14da8ff
Waiting for read() in NIOBlocked@b280d5
ClosedByInterruptException
Exiting NIOBlocked.run() NIOBlocked@14da8ff
AsynchronousCloseException
Exiting NIOBlocked.run() NIOBlocked@b280d5
2015-09-07 11:44:36 -06:00
*/