can the main thread die before the child thread

15,436

Solution 1

From http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html :

The Java Virtual Machine continues to execute threads until either of the following occurs:

  1. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

  2. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

In your case, when the main thread dies, the JVM does not exit, because you still have the created threads running, and they're daemon by default, because of this:

The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.

Cite: http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)

Solution 2

While the code is executing, take a Full Thread dump and see what all Threads are active.

class AnotherClass {
    public static void main(String arrp[]) throws Exception {
        Thread t = new Thread() {
            public void run() {
                while (true) {
                        // do nothing
                }
            }
        };
        t.start();
            //Sleep for 15 seconds
        Thread.sleep(15000);
    }
}

Compile and Execute it:

$ javac AnotherClass.java
$ java AnotherClass

Find the process:

$ ps -ef | grep AnotherClass

nikunj <<10720>> 10681   2 12:01:02 pts/9       0:04 java AnotherClass
nikunj 10722 10693   0 12:01:05 pts/6       0:00 grep Another

Take the Thread dump:

$ kill -3 <<10720>> 

Output (excerpts):

"main" prio=10 tid=0x00039330 nid=0x1 waiting on condition [0xffbfe000..0xffbfe2a8]
    at java.lang.Thread.sleep(Native Method)
    at AnotherClass.main(AnotherClass.java:12)

"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
    at AnotherClass$1.run(AnotherClass.java:7)

Take Another Thread dump (after 15 seconds):

$ kill -3 <<10720>> 

New Output (excerpts):

"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
    at AnotherClass$1.run(AnotherClass.java:7)

Conclusion: main is gone.

Share:
15,436
randeepsp
Author by

randeepsp

learning to learn.......

Updated on July 30, 2022

Comments

  • randeepsp
    randeepsp over 1 year

    I believe that the main thread cannot die before the child thread. But is there any way to check that ? I wrote a simple program below. Can anyone prove it practically leaving theory aside ?

    class childre extends Thread
    {   
        public void run()
        {   
            for( int i=0 ; i<10 ;i++)
            {
                System.out.println( " child " + i);
    
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
            }
        }
    }
    
    public class ChildThreadb4main
    {
    
    /**
     * @param args
     */
        public static void main(String[] args)
        {
        // TODO Auto-generated method stub
    
            System.out.println("main");
    
            childre c1 = new childre();
    
            c1.start();
            for(int i=0;i<5;i++)
            {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println( " child thread alive ? " + c1.isAlive());
        }
    }
    

    After suggestion from James. I tried the following program.

    public class MainChildDie {
    
        public static void main(String ar[]){
    
            final Thread mainThread = Thread.currentThread();
            System.out.println("main run ");
    
            new Thread(){           
    
                public void run(){
    
                    Thread childThread= Thread.currentThread();
                    for(int i=0; i<10;i++){
                        System.out.println( "child"+i);
    
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("main alive  " + mainThread.isAlive());
                }
            }.start();      
        }
    }
    
  • Manish
    Manish over 12 years
    To add on, there is no concept of Parent-Child thread(and there is no such thing as a child thread). Each thread is an independent entity on its own.
  • ammaciel
    ammaciel over 12 years
    @ManishSharma - correct, there's almost no tie except for things like the daemon status carrying over.
  • randeepsp
    randeepsp over 12 years
    Agreed. Is there no way to check the status of the thread name main ?
  • Stephen C
    Stephen C over 12 years
    @ManishSharma - clearly there is such a concept, because you and I both know what the OP means when he talks about a thread being a child of another one. However, this concept has (almost) no support in Java's threading model.
  • Stephen C
    Stephen C over 12 years
    "Is there no way to check the status of the thread name main" - it is only possible if you use the ThreadGroup APIs to enumerate all threads, and search for one whose name is "main". Even then, thread names are not unique.
  • ammaciel
    ammaciel over 12 years
    @randeepsp - There's nothing stopping you from storing Thread mainThread = Thread.getCurrentThread() somewhere at the start of the main function. Then you can check mainThread.isAlive(); Haven't tried it but I suspect it'd work.
  • Manish
    Manish over 12 years
    @StephenC: I should have mentioned "in java programming context", because that is what I was referring to.
  • randeepsp
    randeepsp over 12 years
    @James.Thanks . You are right. Please see the recent program.
  • Stephen C
    Stephen C over 12 years
    @ManishSharma - that doesn't make any difference. We are clearly all talking about thread child/parent in the context of Java programming, so the concept clearly exists. Even the Thread javadocs uses the term "parent thread". But as I said, it is not a concept that is supported by the thread model / APIs.
  • randeepsp
    randeepsp over 12 years
    @ James and @ Amit Im a little confused now. if i add --System.out.println(Thread.currentThread().getThreadGroup()‌​.activeCount()); -- into the inner class run method of MainChildDie class, then it returns active count as 2. while the previous statement says main alive false ? what do they signify now ?
  • randeepsp
    randeepsp over 12 years
    i dont want to do that. i want to check practically if thread names main can die before other threads it has spawned.
  • Amit Gupta
    Amit Gupta over 12 years
    @randeepsp, I believe the thread executing main has finished its execution, and the thread is dead. Activecount is somehow looks confusing to me as well, as its said in thr API that it should be used onlu for informative purpose only. I have also forced the main thread to throw Exception and it terminated while the thread created by it was still running in the background and the activeCount was still two. So it confused me and led me to think that main thread is still active.
  • UndefinedBehavior
    UndefinedBehavior over 8 years
    @James you mean "they're non-daemon by default". The main thread is non-daemon and so its "child" threads are non-daemon by default.