Regarding jvm termination when main method terminates - java

In an interview there was a question was being asked from me...
The JVM exits when ‘main ()’ method reaches its end.
(Circle ONE choice)
Always true
Not necessarily
Always false
None of the above
what i have answered to this question is Not necessarily , please advise is it the correct approach.

The answer is Not necessarily. The JVM terminates when all non-daemon threads in the system have terminated.
The JVM can terminate when Daemon threads are running in it. Since daemon threads are usually used for clean up tasks, it makes little sense to keep JVM alive when only daemon threads are running.

Not necessarily
Depends on the Non demons threads present in your program.
main() is a non-demon thread.
For example you have 3 non-demon threads t1, t2, and main().
For the completion of your program, all these threads are required to be completed or terminated.

Related

difference between wait() and yield()

So far what I have understood about wait() and yield () methods is that yield() is called when the thread is not carrying out any task and lets the CPU execute some other thread. wait() is used when some thread is put on hold and usually used in the concept of synchronization. However, I fail to understand the difference in their functionality and i'm not sure if what I have understood is right or wrong. Can someone please explain the difference between them(apart from the package they are present in).
aren't they both doing the same task - waiting so that other threads can execute?
Not even close, because yield() does not wait for anything.
Every thread can be in one of a number of different states: Running means that the thread is actually running on a CPU, Runnable means that nothing is preventing the thread from running except, maybe the availability of a CPU for it to run on. All of the other states can be lumped into a category called blocked. A blocked thread is a thread that is waiting for something to happen before it can become runnable.
The operating system preempts running threads on a regular basis: Every so often (between 10 times per second and 100 times per second on most operating systems) the OS tags each running thread and says, "your turn is up, go to the back of the run queue' (i.e., change state from running to runnable). Then it lets whatever thread is at the head of the run queue use that CPU (i.e., become running again).
When your program calls Thread.yield(), it's saying to the operating system, "I still have work to do, but it might not be as important as the work that some other thread is doing. Please send me to the back of the run queue right now." If there is an available CPU for the thread to run on though, then it effectively will just keep running (i.e., the yield() call will immediately return).
When your program calls foobar.wait() on the other hand, it's saying to the operating system, "Block me until some other thread calls foobar.notify().
Yielding was first implemented on non-preemptive operating systems and, in non-preemptive threading libraries. On a computer with only one CPU, the only way that more than one thread ever got to run was when the threads explicitly yielded to one another.
Yielding also was useful for busy waiting. That's where a thread waits for something to happen by sitting in a tight loop, testing the same condition over and over again. If the condition depended on some other thread to do some work, the waiting thread would yield() each time around the loop in order to let the other thread do its work.
Now that we have preemption and multiprocessor systems and libraries that provide us with higher-level synchronization objects, there is basically no reason why an application programs would need to call yield() anymore.
wait is for waiting on a condition. This might not jump into the eye when looking at the method as it is entirely up to you to define what kind of condition it is. But the API tries to force you to use it correctly by requiring that you own the monitor of the object on which you are waiting, which is necessary for a correct condition check in a multi-threaded environment.
So a correct use of wait looks like:
synchronized(object) {
while( ! /* your defined condition */)
object.wait();
/* execute other critical actions if needed */
}
And it must be paired with another thread executing code like:
synchronized(object) {
/* make your defined condition true */)
object.notify();
}
In contrast Thread.yield() is just a hint that your thread might release the CPU at this point of time. It’s not specified whether it actually does anything and, regardless of whether the CPU has been released or not, it has no impact on the semantics in respect to the memory model. In other words, it does not create any relationship to other threads which would be required for accessing shared variables correctly.
For example the following loop accessing sharedVariable (which is not declared volatile) might run forever without ever noticing updates made by other threads:
while(sharedVariable != expectedValue) Thread.yield();
While Thread.yield might help other threads to run (they will run anyway on most systems), it does not enforce re-reading the value of sharedVariable from the shared memory. Thus, without other constructs enforcing memory visibility, e.g. decaring sharedVariable as volatile, this loop is broken.
The first difference is that yield() is a Thread method , wait() is at the origins Object method inheritid in thread as for all classes , that in the shape, in the background (using java doc)
wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
and here you can see the difference between yield() and wait()
Yield(): When a running thread is stopped to give its space to another thread with a high priority, this is called Yield.Here the running thread changes to runnable thread.
Wait(): A thread is waiting to get resources from a thread to continue its execution.

Yield Method confusion

I have a confusion. I read somewhere that Thread.yield() method causes the currently running thread to pause and give chance to remaining thread of "Same Priority".
Now always it is same priority threads executed or higher priority threads can also be executed. And if suppose currently running thread has some lock on some object, after executing yeild method will it give its lock?
When you call Thread.yield() the current thread pauses and allows the scheduler to run a different thread. Priorities are managed by the scheduler.
And no, of course not - you don't release any locks. Doing so would break synchronization.

Terminate Main Thread without ensuring the termination of threads spawned by it

I have implemented a multi-threaded program which involves spawning a thread for each user,and performing some minor activities(No exhaustive processes like database connection involved).The main thread runs infinitely,and its termination is handled via monitoring file creation activity.
My question is, is it okay to terminate the main thread straightaway,without waiting for the threads to finish ? (assuming that the threads would complete on their own(!),could be a false assumption).
Sure.
The main thread is just one thread amongst others and its termination won't affect the other threads (unless you don't use System.exit() to stop the thread...).
The main thread is just the first thread*) that has been started but it has no extra or hidden features or functionalities.
*) to keep it simple - the jvm may have started some internal threads before main - but the application has no code for those threads
Yes, The point of threads is that they run independently.
It would only matter if your client threads were started as daemon threads and main is the only non-daemon thread. (In which case, the application would shutdown when it stops)
Yes and usually that's the case in most applicaitons. The main thread usually is repsonibly for initiating the system and it can peacefully die after that.
Note that you don't really "terminate" themain thread, instead just let it complete its run method. And thats ok.

Is it bad for a java application to shutdown while a separate thread is sleeping?

For example if i have a java command line program that spawns a new thread (thread #2) to do some polling, and then sleep for 5 minutes. while the main thread (thread #1) of the program is running and then finishes before the 5 minutes from thread #2 is up, so the program will exit. Is there any problem with this? Should I interrupt Thread #2 in Thread #1 before the end of the main function in this program?
It may be considered bad practice and a sign of poor design by some, but in principal there shouldn't be any problem to terminate the JVM with System.exit. Not if there is no clean-up to be performed by Thread #2.
Another issue though, is whether or not Thread #2 may be in the middle of some action.
It depends entirely on what it's doing. When the program exits, the process will terminate, taking any additional threads with it. The only potential problem would be if Thread #2 holds some resource handle. However, if all it's doing is reading, then you shouldn't have a problem.
Non-deamon threads keep on running in the background after main has finished execution.
As a result you will have hunging threads unless you explicitly call System.exit which kills all threads.
The best approach though would be to stop the thread#2.
Just use a status flag e.g. boolean die in thread#2.
Thread#1 will interrupt the thread#2, thread#2 will then see the die flag (set by thread#1) set to true, will do any clean up necessary and exit gracefully.
In your case that thread#2 is just sleeping for 5 mins and not doing anything it will be fine.
Have a look at here.
For the termination of a java program, it is necessary for all non-daemon threads to terminate first.
Once all the non-daemon threads stop their execution, the JVM will kill off all the daemon threads and thus will get shut-down.
In you case, there should not be any problem, unless and until your Thread #2 is doing some important function like handling resources.

Is there a timeout for threads waiting on a synchronised method in Java?

Is there a default timeout for threads waiting on a synchronised method in Java? Some threads in my app are not completing as expected. Is there anyway to check whether threads have died as a result of timeouts?
The JLS does not specify any timeout for synchronized sections. It just mentions
While the executing thread owns the
lock, no other thread may acquire the
lock.
You can set a timeout on the join() method to make sure you don't wait forever.
I'd have a look at the java.util.concurrent packages to see if there were new features added to help your situation.
I'd also recommend "Java Concurrency In Practice" by Brian Goetz. (I need to re-read it again myself.)
If a method is waiting on a synchronization object it should never die, but it could be waiting for an awfully long time (as in, "forever") if something goes wrong. Perhaps your program is never releasing a lock on a resource?
Threads in Java don't just die suddenly. Either they are not progressing (blocked on a lock or infinite loop or similar), or if an exception is thrown and it is not handled, then the thread's execution will stop when the exception propagates to the top level (which should then print the exception's stack trace to System.err).
If your application is deadlocking, one way to find out the reason is to make a thread dump. The JVM can also itself detect simple deadlocks, in which case it will report them in the thread dump.
You can generate a thread dump under Linux by running kill -QUIT <pid> and under Windows by hitting Ctrl + Break in the console window. Or even simpler, use VisualVM, StackTrace or a similar tool.
I suggest you use kill -3 to see a thread dump, and then see what the problematic threads are.

Categories

Resources