Two Laptop Bag*
The moose likes Threads and Synchronization and the fly likes Stop blocked thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Stop blocked thread" Watch "Stop blocked thread" New topic
Author

Stop blocked thread

Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Hi,

How to stop a thread that is blocked by IO read?



This example will try to interrupt a thread but that will not break out of IO wait...
The only way to stop this thread is to close the reader first.
So what is the right way?

Thanx.
Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Now this is good one

I changed the code to close the InputStream in the interrupt method.

But due to the way Reader is implemented, it causes dead lock.
The interrupt is called by the main thread and the main thread is trying to close the stream, but even thou the close is not synched, in the source it tries to get the lock on itself. So since my reader is blocked in the readLine() method which also locks, i get the deadlock!



The code will work fine if the reader is not blocked.

So how can one stop a thread that was blocked in IO?!
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Yaroslav Chinskiy:
Now this is good one

I changed the code to close the InputStream in the interrupt method.

<code deleted>

The code will work fine if the reader is not blocked.

So how can one stop a thread that was blocked in IO?!


If the InputStream is blocked on a Socket or Process, you must close that, not the InputStream to interrupt the read. In this case Process.destroy(). In the case of a file the read won't block for long.
Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Thank you for the reply.

That is what i changed my code to. I did not think that its the good idea because I had to make Process variable available outside of the method.

I guess its not a big deal.

But i was surprised to see the deadlock.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Stop blocked thread