I have a thread that's reading from an input stream, and (just for simplicity) printing it back out to the console. See below for the code snippet.
I want to be able to terminate this thread at some point, so I should be able to do this by closing the input stream. This should cause an exception to be thrown, interrupting the BufferedReader::readLine
method, closing the thread.
For some reason, the close()
invocation just hangs.
What's the reason that this is happening? Is there a way I can close down the thread without requiring the user to input any further text?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception {
ReaderTest readerTest = new ReaderTest(System.in);
new Thread(readerTest).start();
Thread.sleep(1000L);
System.out.println("About to close...");
System.in.close(); // Should cause thread to throw exception and terminate, but just hangs
System.out.println("All closed...");
}
private static class ReaderTest implements Runnable {
private final InputStream inputStream;
public ReaderTest(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}