2015-09-07 11:44:36 -06:00
|
|
|
|
// concurrency/CloseResource.java
|
2015-11-14 16:18:05 -08:00
|
|
|
|
// <20>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.
|
2015-06-15 17:47:35 -07:00
|
|
|
|
// Interrupting a blocked task by
|
|
|
|
|
// closing the underlying resource.
|
|
|
|
|
// {TimeOutDuringTesting}
|
|
|
|
|
import java.net.*;
|
|
|
|
|
import java.util.concurrent.*;
|
|
|
|
|
import java.io.*;
|
|
|
|
|
|
|
|
|
|
public class CloseResource {
|
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
|
|
|
ExecutorService exec = Executors.newCachedThreadPool();
|
|
|
|
|
ServerSocket server = new ServerSocket(8080);
|
|
|
|
|
try(InputStream socketInput =
|
|
|
|
|
new Socket("localhost", 8080).getInputStream()) {
|
|
|
|
|
exec.execute(new IOBlocked(socketInput));
|
|
|
|
|
exec.execute(new IOBlocked(System.in));
|
|
|
|
|
TimeUnit.MILLISECONDS.sleep(100);
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("Shutting down all threads");
|
2015-06-15 17:47:35 -07:00
|
|
|
|
exec.shutdownNow();
|
|
|
|
|
TimeUnit.SECONDS.sleep(1);
|
2015-12-02 09:20:27 -08:00
|
|
|
|
System.out.println(
|
|
|
|
|
"Closing " + socketInput.getClass().getName());
|
2015-06-15 17:47:35 -07:00
|
|
|
|
socketInput.close(); // Releases blocked thread
|
|
|
|
|
}
|
|
|
|
|
TimeUnit.SECONDS.sleep(1);
|
2015-12-02 09:20:27 -08:00
|
|
|
|
System.out.println(
|
|
|
|
|
"Closing " + System.in.getClass().getName());
|
2015-06-15 17:47:35 -07:00
|
|
|
|
System.in.close(); // Releases blocked thread
|
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
|
}
|
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
|
Waiting for read():
|
|
|
|
|
Waiting for read():
|
|
|
|
|
Shutting down all threads
|
|
|
|
|
Closing java.net.SocketInputStream
|
|
|
|
|
Interrupted from blocked I/O
|
|
|
|
|
Exiting IOBlocked.run()
|
|
|
|
|
Closing java.io.BufferedInputStream
|
|
|
|
|
Exiting IOBlocked.run()
|
2015-09-07 11:44:36 -06:00
|
|
|
|
*/
|