0

I am trying to shutdown the application, whenever any Fatal Error/Exception comes but before shut down the application my current thread/task should complete, so I have written mainThread.join() inside run(), its working fine when there is no exception. But whenever my doTask() throwing exception that time join() waiting forever.

public class POC 
{
    public void doTask() throws Exception
    {
        throw new Exception("Fatal Error");
        //throw new Exception("Fatal Error"); By commenting working fine.
    }

    public static void main(String[] args) 
    {
        POC ob = new POC();
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            public void run()
            {   
                try 
                {
                    System.out.println("Join() Start");
                    mainThread.join();
                    System.out.println("Join() End"); //Why this is not printing?
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }               
            }
        });

        try 
        {   
            System.out.println("Before doTask()");          
            ob.doTask(); //User Defined Run()
            System.out.println("After doTask()");
        }
        catch (Exception ex)                    // FATAL
        {
            System.err.println("Exception : " + ex.getLocalizedMessage());
            System.exit(-1);
        } 
    }
}

OutPut    :    0
Before Run()
Exception : Fatal Error
Join() Start

Why System.out.println("Join() End"); is not printing?

qwwdfsad
  • 3,077
  • 17
  • 25

1 Answers1

1

You have a simple deadlock. When you throw an exception, exception handler call System.exit(-1), which is blocking, see javadoc:

Terminates the currently running Java virtual machine by initiating its shutdown sequence

...

The virtual machine's shutdown sequence consists of two phases. In the first phase all registered #addShutdownHook shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish.

So main thread is waiting in System#exit call until all shutdown hook will be finished and your only shutdown hook blocks and waits until main thread will finish (which is waiting in System#exit ... GOTO 1).

Community
  • 1
  • 1
qwwdfsad
  • 3,077
  • 17
  • 25