There is an infinite input stream and I read incomming massages with following simple lines of code:
InputStream inputStream = response.getBody();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
while ((event = reader.readLine()) != null) {
// do the work
}
}
System.out.println("Connection closed");
And everything is fine. But I want to be able to drop the connection if a certain amount of time there is no new messages.
The first problem was that readLine
method blocks execution until the next message receiving. That's what I want to avoid. And I found this implementation of CloasableReader - wrapper over Bufferedreader that allows interrupting readLine
from outside. So I just replaced BufferedReader with CloasableReader and voalá - I exited the while loop. But the line with "Connection closed" message still wasn't executed.
I changed the code a little bit...
InputStream inputStream = response.getBody();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((event = reader.readLine()) != null) {
// do the work
}
} finally {
if (reader != null) {
reader.close();
}
}
System.out.println("Connection closed");
...and realized that actually close
method also stucks waiting until next message receiving. Because of that Guava's TimeLimiter::callWithTimeout
method didn't work for me. Actually it works fine (wrapping the code marked as "do the work" in the example above) but I cannot leave the try-catch-finaly block.
Internally BufferedReader::close
calls InputStreamReader::close
which calls InputStream::close
and here is the problem. I'm just waiting and will do it forever.
I have no idea what to do now. How to force closing the stream?