2

I am having an interrupted exception in my code and I am trying to understand why.

What happens is that I am trying to create files in some place in my file system by calling FilesUtils.filesMethod().

If I get an IOException I try to sleep for 100 ms. During the sleep I need to check if I am interrupted (because InterruptedException is a check exception with sleep).

if so I print "Got interrupted" and get the interrupt flag of the current thread to true.

I am getting "Got interrupted" printed to my log.

Nowhere in my code there is the command interrput() to this thread.

what could it be?

could this senario makes sense:

  1. the method of ilesUtils.filesMethod() throws InterruptedIOException because the stream was closed under the threads feets. Also this InterruptedIOException set the Interrupted flag to true.

  2. I catch InterruptedIOException in my catch (IOException e).

  3. The sleep checks if Interrupted flag is true. it is (see 1) so it throws InterruptedException.

could this be the case?

        try {
            FilesUtils.filesMethod();
            break;
        } catch (IOException e) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e1) {
                log.info("Got interrupted", e1);
                Thread.currentThread().interrupt();
            }
        }
Yotam Eliraz
  • 107
  • 2
  • 8

1 Answers1

1

Without knowing the implementation details of Your FilesUtils.filesMethod(), We can only guess what is happening here. But just throwing InterruptedIOException does not cause interrupt flag to be set.

I am guessing FilesUtils.filesMethod() sets the interrupt flag before throwing the InterruptedIOException and then sleep method throws InterruptedException (because interrupt flag is set).

You can clear the interrupt flag with Thread.interrupted() before calling sleep method (if You want to be able to sleep in this case). So sleep method does not throw InterruptedException.(If the thread does not get interrupted again)

miskender
  • 7,460
  • 1
  • 19
  • 23
  • 1
    Thanks. just saw that the sleep() method throws InterruptedException during debug. I tried to clear the flag by Thread.interrupted() in debug mode and then running the sleep again - but (!) and here is the interesting part - it didn't work. Even after Thread.interrupted() the sleep still throw InterruptedException. I even check the flag in debug mode - it was false. Any idea why the sleep could thrown this InterruptedException?? Thanks! – Yotam Eliraz Feb 15 '19 at 21:50
  • 1
    @YotamEliraz There are two case that I can think of, First If this method called from ExecutorService, calling shutdownNow() for ExecutorService causes its pooled threads' interrupt flag to be set. Second interrupt() called for this thread.(But You said there is no such call). – miskender Feb 16 '19 at 13:29