Can the JVM continue running after the main METHOD has ended? [duplicate] - java

I read this statement:
The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.
Is it true?
I also came to know "Even if the main thread dies, the program keeps running".
This is my current understanding:
When you start a program, the JVM creates one thread to run your program.
The JVM creates one user thread for running a program. This thread is called main thread.
The main method of the class is called from the main thread.
If a program spawns new threads from the main thread, the program waits until the last thread dies.
Which one is true?

The program terminates when all non-daemon threads die (a daemon thread is a thread marked with setDaemon(true); it's usually used for utility threads). From the documentation:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
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.

I read this statement: “The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.”Is it true?
No, it is not. The virtual machine terminates if the last non-daemon thread has finished. It doesn't have to be the main thread.
Simple example:
public static void main(String[] args) {
System.out.println("Main thread started");
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Second thread started");
try {
Thread.sleep(2000); // wait two seconds
} catch(Exception e){}
System.out.println("Second thread (almost) finished");
}
}).start();
System.out.println("Main thread (almost) finished");
}

When the main thread stops, the program terminates.
The program terminates when there no longer is any non-daemon thread running (or someone called System.exit). The main thread can have finished long ago.

The JVM will exit when the main thread and all non-daemon threads finish execution.
When you create a new thread, you can call Thread.setDaemon(true) to make it a daemon thread. If you do this, then the JVM will not wait until this thread finishes before execution. This is useful for any threads you create which are made to run in the background until the program stops.
If you create a new thread and do not call Thread.setDaemon(true), then the JVM will delay exit until this thread is complete, even if the main thread is finished.

When the main thread was start it'll not wait for the another thread which was created by us until they if can't use the join() of the thread class to wait for this thread. So basically if the child thread or sub thread getting more time for processing the task and you don't use the join() then main thread may be stop. To keep with main thread you must use the join() so the main thread stop after only this related thread are stop
check this link
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join%28%29

The first statementis not exact.
The java program terminates when all non-daemon threads has been terminated or when System.exit() or Runtime.exit() is invoked.
Thread is terminated when it exited its run() method. Main thread is special because you do not explicitly implement its run() method, you implement main() instead and the main() is called from run(). So, main thread is terminated when main() is terminated.
But main thread is not neccessarely the last one.

This is the from the JVM specification 3rd Draft, so it's the most current I'm aware of:
5.7 Virtual Machine Exit
The Java virtual machine terminates all its activity and exits when either:
• All threads that are not daemon threads terminate.
• Some thread invokes the exit method of class Runtime or class System, and
the exit operation is permitted by the security manager.
There is no distinction made about the main thread, so we shouldn't assume that is the only one that it applies to.

Related

Thread termination order

As I was learning multithreading in java, i came to know that there is no execution order for threads.
As per my understanding is below statement true?
A user thread (which is not a Daemon Thread) it should terminate before termination of main thread.
I have read similar links:
if main method completes the execution, what happens to any long running thread?
When does the main thread stop in Java?
I have a program to demontrate, please correct me.
class ThreadDemo {
public static void main(String args[]) {
Thread t = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Within 'Child Thread' # "+System.currentTimeMillis());
}
}, "Child Thread");
//t.setDaemon(false);
t.start();
System.out.println(Thread.currentThread()+" thread is alive:"+Thread.currentThread().isAlive());
System.out.println(t+" thread is alive:"+t.isAlive());
System.out.println("'Main' thread exiting # "+System.currentTimeMillis());
}
}
Most of the times output to this program on my system is
'Main' thread exiting # 1406971862950
Within 'Child Thread' # 1406971862952
Does this mean that main thread exits before child thread? If yes, then why is this happening?
That's true. When you execute your program, a main thread is created which executes the main method. Since you are creating another thread in main, both the created thread and main thread will execute parallerly irrespective of each other.
However if you require your created thread to complete executing and than main finishing the execution jst add followind code after starting your thread.
t.join();
This would force your main thread to stop until your created thread finishes execution.
Daemon threads are the threads that are pulled automatically by the JVM as and when required. Garbage collector is one among.
Main thread is pulled by user. So it ia non-daemon thread.
JVM shuts down only when all non-daemon threads complete execution. It does not wait for daemon threads to complete.

How start method of Thread class create a new stack and execute run method

Can some body help me to understand my below questions:-
When new stack is created? On executing Thread t=new Thread() or t.start()
How start() method calls implemented run()?
Can we assign memory to each thread like JVM? If NO, how JVM will modify stack memory of running thread.
From the Javadoc of Thread:
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
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.
Now, to your questions.
When [is a] new stack is created? On executing Thread t=new Thread() or t.start()?
A new thread is created by the constructor. It is run with the start method.
How [does] start() method calls implemented run()?
From the source code of Thread:
public void run() {
if (target != null) {
target.run();
}
}
Can we assign memory to each thread like JVM? If No, how JVM will modify stack memory of running thread.
No, you cannot assign memory to each thread. The operating system (Windows, Unix, OS X) controls how threads are created and destroyed. The JVM has access to every thread through a string identifier.
You can read the Thread source code for more information about the Thread class.
The Stack is created while the Start() method is called as till then the required info to create
the stack is not available.
The Thread class you call has this coded behind that calls run within its start method.
[In fact it is the Start() method that actually creates a new thread (not Thread class but the
real process thrad) and calls run() in the new thread. for eg: if you call run() instead of start
() in your runnable class. No new thread will be created.]
No. We cant assign Specific amount of memory to a thread.

Is a thread guaranteed to have started when Thread.start() returns?

I have tried some sample code along the lines of:
Thread thread = new TestThread();
thread.start();
thread.isAlive();
It appears to me that the only way for the isAlive() call to return false, is for the thread to have already finished. Is this true?
The Java 7 JavaDoc for start:
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
The Java 7 JavaDoc for isAlive:
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
Neither of these seem very conclusive to me.
The statement someThread.start() will cause that thread to go into
runnable state
It is not guaranteed that it will start executing its run method immediately after start() is called.
Exactly when to execute the thread, is totally dependent on the thread scheduler.
When someThread.start() is called, the thread can move from runnable to runing state and even waiting state.
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
This means, the thread is alive when its start() is called and its run() not completed yet. Completion of run() method means thread is dead.
Thread has started doesn't mean it is already executing run method but it's status is Alive.
So after start is returned Thread is alive but not guaranteed to be executing run method it's state can be anything except New after completion of start method. (Runnable, Waiting, Terminated, etc)
t.isAlive() returns true if t is not in the NEW or TERMINATED state
Also take a look at this great resource on java threading
A thread t is alive as soon as t.start() returns and until t.run() completes.

Does Application main method wait for Threads before it terminate

Suppose I jave a Java application which have a Thread running inside it's main method.
after all the code in the main method get executed. would the application wait for the Thread until it finish executing, or it will just terminate the application and the JVM.
From java.lang.Thread documentation:
When a Java Virtual Machine starts up, there is usually a single
non-daemon thread (which typically calls the method named main of some
designated class). The Java Virtual Machine continues to execute
threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
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.
So, yes, it will wait, but not for threads marked as daemon threads.
You could see it working with the following code:
public class ThreadTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I'm still here!");
}
});
// uncomment following line to test with daemon thread
//thread.setDaemon(true);
thread.start();
System.out.println("Finished!");
}
}
It depends what kind of threads the started threads are. The JVM exits when the only threads running are all daemon threads.
By default, threads are not daemon threads. To make a thread a daemon thread, call Thread.setDaemon(true) before startin it.
Would the application wait for the Thread until it finish executing
Yes, It would wait to execute complete the child thread whether main thread is completely executed or not.
It will not wait for daemon threads. If thread set as Daemon thread by calling Thread.setDaemon(true);

Why does a thread outlive the main method in Java?

I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The run method just prints "Hello World", sleeps for a second, and repeats.
In my main method, I have:
public static void main(String[] args) {
Thread thread = new Thread(engine);
thread.start();
System.out.println("Done.");
}
As I expected, I see "Hello World" and "Done." printed quickly, meaning the main method has reached the end, but what I didn't expect was that the thread I started kept running even after the end of main was reached.
Why does the program continue to execute even after main exits? I would have thought that when main exited the process would terminate and all of the threads would be cleaned up forcefully. Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?
Because that's how it works. The program exits when System.exit() is called, or when the last non-daemon thread stops running.
And it makes sense. Without this rule, every Java program consisting in just spawning a GUI, for example, would have to wait() infinitely to avoid the program from exiting immediately.
If you want your program to exit when the main method finished, consider making your threads daemons. But take care of the fact, that daemon threads will be aborted, when main finishes.
You can create a daemon thead like so:
Thread t = new Thread(...);
t.setDaemon(true);
All non-daemon threads are user threads. Those threads are stopping the jvm from closing.
User threads continue to run independently of the lifetime of their parent thread, i.e, the creator thread. So, you have to join the threads explicitly by invoking Thread.join before the main thread terminates.
From the Javadoc of Thread:
When a Java Virtual Machine starts up, there is usually a single
non-daemon thread (which typically calls the method named main of some
designated class). The Java Virtual Machine continues to execute
threads until either of the following occurs:
The exit method of class Runtime has been called and the security
manager has permitted the exit operation to take place.
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.
If you want JVM to terminate even if a thread t is running, you should make thread t a daemon thread:
t.setDaemon(true);
There are two types of threads, user and daemon. The process terminates when there are no more user threads. The main thread is always a user thread. The thread that you start is also a user thread, and therefore keeps the process alive for as long as it runs.
Calling setDaemon(true) on your thread before you start it will make your process terminate (more or less) as soon are your main() function returns.
The Java Language Specification section 12.8 indicates:
12.8. Program Exit
A program terminates all its activity and exits when one of two things
happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System,
and the exit operation is not forbidden by the security manager.
This means it is not enough for the main thread to finish.
If you do want it to exit when the main thread ends you need to either make the new thread a daemon by using Thread#setDaemon or use Thread#join as you initially suggested.
The main thread is also a user thread which is being created and its lifecylce is similar to any other user thread for that matter.
The other user threads are not dependent on the main thread for any reason unless you set the threads as daemon threads.
Once the main thread completes its work it ends(it neither ends the other user threads nor will end the process because the other user threads are running).

Categories