prashant
prashant

Reputation: 219

Java stopping a thread blocked on input stream read

From what I understand, once a thread has been started, it can either complete its operation and stop automatically, or if its performing some work in a loop, then Thread.isInterrupted() needs to be checked periodically to determine if it needs to exit the loop.

public void run() {

  //initialize input stream
  .....
  byte[] buffer = new byte[1024];
  int len = -1;
  while((len = inputStream.read(buffer)) != -1 && 
 !Thread.isInterrupted()) {
  //write the buffer to some output stream

 }

}

But, lets assume that the Thread is stuck in a call to :-

public void run() {
//initialize input stream
.....
    InputStream.read(buffer)
    here, buffer = new byte[FILE_SIZE]
    and FILE_SIZE = 100 * 1024 * 1024;//100 MB
}

Then how can we stop this running thread in this scenario?

Upvotes: 0

Views: 1746

Answers (1)

Marinos An
Marinos An

Reputation: 10880

This can happen if you know the actual stream type. e.g. in case of BufferedInputStream you could use available(), to find out how many bytes can be read without being blocked.

Normally to be able to interrupt the thread execution, you should try to read the stream using smaller buffer.
But if you expect that despite the small buffer size the read operation can still block for long, and you want to be able to stop at that point, you can write your code in a way that is prepared for receiving a Thread.stop() (e.g. if thread has not stopped 5 seconds after sending interrupt() ).

Upvotes: 1

Related Questions