0

I have a method which scraps data from a website inside a thread and then give me a total count of data retrieved.

When i press cancel button Thread.interrupt() is called and data is scrapped for a few seconds and then it stops and give me a total count of data retrieved.

Does calling Thread.interrupt() stops a thread from executing immediately or does it take few seconds to completely stop?

2 Answers2

0

Sending an interrupt to a thread does, in itself, nothing at all to stop the thread.

It is only when the code running on that thread, takes the interrupt status into account, that that code can respond to an interrupt to stop doing what it is doing, at its earliest convenience. How soon that is, depends entirely on that code.

Some code can even ignore the interrupt status. And some code is even unable to respond to an interrupt status immediately (blocking IO comes to mind).

bowmore
  • 10,842
  • 1
  • 35
  • 43
  • Then how do i make the function take interrupt status into account? –  Jan 08 '18 at 06:34
  • @ProgrammingLycan if it's your method, by checking for it. If it's not your method, you can't. Assuming the method doesn't already use something that checks for it. – Kayaman Jan 08 '18 at 06:37
0

Thread.interrupt() will not stop thread.It only signal the thread to stop.It is the code need to poll and check the status and handle appropriately .

If this thread is blocked in an invocation of the wait() methods of the Object class, or of the join(),sleep() methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

gati sahu
  • 2,576
  • 2
  • 10
  • 16