1

I have a thread which runs a task of file parsing. Its set as a daemon thread which runs in background from tomcat startup to shutdown doing its task.

I am looking to handle thread termination upon interruption and server shutdown. I want to know if am going about correctly.

class LoadingModule{             // Thread is started from here
    threadsStartMethod() {
        Thread t = new Thread(FileParseTask);
        t.setDaemon(true);
        t.start();
    }
}

Class FileParseTask implements Runnable {

    @Override
    public void run() {
        try {
            while(!Thread.currentThread.isInterrupted) {
                // poll for file creation
                // parse and store
            }
        } catch(Exception exit) {
            log.error(message);
            Thread.currentThread.interrupt();
        }
    }
}

would this cleanly exit the thread in all scenarios?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39

1 Answers1

1

it would depend on the code inside the loop. If the code inside the loop captures the interrupted exception and recovers, you will never see it. Also generic exception "exit" hides other exceptions. Change the code so you know what hit you.

I would do the following

Class FileParseTask implements Runnable {

    @Override
    public void run() {

            while(!Thread.currentThread.isInterrupted) {
                try {
                // poll for file creation
                // parse and store
                } catch(Exception exit) {
                    if (InterruptedException)
                         break;
                    else{
                      //
                    }
                    log.error(message);
                }
            }
    }
}

This has worked for me with up to 2K threads with no problems

bichito
  • 1,406
  • 2
  • 19
  • 23
  • Do I need to invoke Thread.CurrentThread.interrupt() in catch block in order to set interrupt flag to true ? OR does while(!Thread.CurrentThread.isinInterrupted) automatically gets the value as true upon some interruption ? – Rk R Bairi Jan 27 '17 at 17:11
  • Probably not. if you are inside the if (instanceof Interruptedexception) block I think you have enough info to break out of the loop. Also you can check the state of the current thread if you need to – bichito Jan 27 '17 at 17:19
  • why invoke interrupt() from catch http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception – Rk R Bairi Jan 27 '17 at 17:25
  • That's why I said probably not. In my case there was no need to broadcast the state because there was nobody else interested in the interruption. In your case it may make sense since you are not using any shutdown hook. It does not hurt to set the right state – bichito Jan 27 '17 at 18:17