how to download file using interruptiblechannel? (NIO)
When I got an incoming call then I have to immediately interrupt my long running thread. I want to use Thread.interrupt() method to do that.
Reference says:
Threads blocked in an I/O operation of an InterruptibleChannel will
have their interrupt status set and receive an ClosedByInterruptException.
Also, the channel will be closed.
In my thread I'm downloading a file via HTTP, so I want to use InterruptibleChannel in order to immediately stop downloading. Could you give me some source code, how to download a file using InterruptibleChannel?
this solution is not okay for me, because Thread.interrupt() doesn't interrupt blocking IO:
while ((length = httpIn.read(buffer)) > 0) {
if(Thread.interrupted())
....
else
{
fileOut.write(buffer, 0, length);
fileSize 开发者_如何学运维+= length;
}
}
One general way to interrupt a thread that is blocked doing I/O is to close the channel. For example, if a thread is blocked in a read() operation over a socket, the thread that want to interrupt it can close the socket. Not sure if this method will be useful for you, but its a general solution that some times it is used.
精彩评论