Jatin
Jatin

Reputation: 31724

stream readLine to close with interruption

I have a thread, which reads input from getInputStream of a Process. It waits for readLine.

BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream));
while(!Thread.currentThread().isInterrupted()){
String s = read.readLine();
process(s);
}

But it turns out that readLine doesn't respond to interrupt status. So during shutdown, it doesn't let the JVM to shutdown. On browsing the source code, it looks that they just poll till the have a \n line terminating character.

Any alternatives or hacks?

PS: It is a duplicate of How to interrupt BufferedReader's readLine. Hence I am closing it

Upvotes: 2

Views: 219

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

From Thread.interrupt

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

But BufferedReader does not implement InterruptibleChannel. So, this is the reason why your thread is stuck in the call to readLine().

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

A reliable way to stop a process is Process.destroy. Save a reference to the process in a field and call Process.destroy instead of interrupting the thread.

Upvotes: 1

LaGrandMere
LaGrandMere

Reputation: 10359

Shouldn't it be :

while(!Thread.currentThread().isInterrupted()){

Upvotes: 2

Related Questions