OnJava8-Examples/threads/CloseResource.java

46 lines
1.4 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/CloseResource.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.
2015-06-15 17:47:35 -07:00
// Interrupting a blocked task by
2016-01-25 18:05:55 -08:00
// closing the underlying resource
2015-06-15 17:47:35 -07:00
// {TimeOutDuringTesting}
import java.net.*;
import java.util.concurrent.*;
import java.io.*;
public class CloseResource {
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
ServerSocket server = new ServerSocket(8080);
try(InputStream socketInput =
2016-01-25 18:05:55 -08:00
new Socket("localhost", 8080)
.getInputStream()) {
es.execute(new IOBlocked(socketInput));
es.execute(new IOBlocked(System.in));
2015-06-15 17:47:35 -07:00
TimeUnit.MILLISECONDS.sleep(100);
2015-11-03 12:00:44 -08:00
System.out.println("Shutting down all threads");
2016-01-25 18:05:55 -08:00
es.shutdownNow();
2015-06-15 17:47:35 -07:00
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
*/