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.
Related
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.
I had a quick question, in Java, is it better to let a thread run continuously after it is done being used, or is it better to try and .interrupt() the thread?
My thought is this: Lets say I create threads by a loop so that I can have 100 threads all doing a separate process that does not interrupt the GUI (on the main thread), then the process is finished on all of the threads. Do I stop the threads, or do I just let them continue being open, even though they are not technically doing anything?
My guess is that it would be best to kill the threads so they do not take any resources from the rest of the program. Any ideas?
When a thread has "finish processing", i.e., exits from the run method, the thread will terminate itself and there's no need to interrupt.
I want to know in Java:
If main thread got killed what will happen to other children threads?
If child thread got killed what will happen to siblings and parent thread?
I read in the following link that since threads sharing address space, killing one thread can affect other thread also.
Below is a quote from here.
Threads are light weight processes that divide main flow of control into multiple flows and each flow of control/thread will execute independently. Activity of the process in a system is represented by threads. The process that has multiple threads is called as multi threaded. Each threads has its own thread ID ( Data Type Integer), register, program counter, stack, error no. Threads can communicate using shared memory within same process.
There are different advantages of using threads to mange and maintain the subtask of applications. When we are using threads than less system resources are used for context switching and increased the throughput of application. Threads also simplify the structure of program. There is no special mechanism for communication between tasks.
Threads also have some disadvantages for example threads are not reusable as they are dependent on a process and cannot be separated from the process. Threads are not isolated as they don't have their own address space. The error cause by the thread can kill the entire process or program because that error affects the entire memory space of all threads use in that process or program. Due to the shared resources by the threads with in the process can also affect the whole process or program when a resource damage by the thread. For concurrent read and write access to the memory thread will required synchronizations. Data of the process can easily damage by the thread through data race because all the threads with in the process have write access to same piece of data.
Can u gys please tell whether whatever told in the above link is applicable to java
1) Nothing will happen to the "child threads"...
2) Nothing will happen to the "sibling threads"...
...with the following exception: If all remaining threads are daemon threads, the application will terminate (i.e., when there are only daemon threads left, these will be killed as well).
From the documentation of Thread:
[...] The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called [...]
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.
Nothing, in both cases. Threads run independantly of one another and there's no such thing as "parent" or "child" threads in this sense. The process will continue to run until there are no threads running in it.
A process is simply a container that contains some threads. The threads execute code. If there is one thread or more running inside a process container, the process will continue to exist. There's no symbiotic relationship between the threads, killing one will not kill another.
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.
I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.
You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().
It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.
So, you can safely sleep on your main thread.
Using a separate thread for the code is your only solution. Every action started by the Swing thread must be delegated to a separate thread if it would otherwise block the GUI.
I wrote a super simple delay function for java that doesn't let your GUI freeze . It has worked everytime i have used it and i guess it will work for you too.
void Delay(Long ms){
Long dietime = System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<dietime){
//do nothing
}
}
For eg : To delay a thread by 5 millisecods use Delay(5L)
And where would one declare this thread. Please bear in mind any, any reference to a function that contains thread sleep will cause the main thread to pause. Because the main thread will have to wait the the sub thread to pause.
The reality is that threads don't realy work as seperate independant thread because a thread must be started from another thread. In other words if you are creating desktop application, and even if you don't work with other threads, your application is a one threaded application. Now if you start working with threads & putting them to sleep, you will soon find out that that you won't be able to do anything else in the application. No & no the other threads won't even run because they are waiting the first thread to finish sleeping. Why is this? Cause the thread are sub threads of the main thread and it is the main thread that is waiting for that sleep sub thread to wake up. You can't design a threadless application either as java is single main threaded application. Any, yes any, thread further defined in your application always runs inside in the main thread.
Unless somebody can prove me wrong, you obviously whould never pause your main thread as this would lock up your app. However as soon you define another thread and suspend it with sleep() this also locks up your app as the thread was defined in subclass of the main application and therefore the main thread.
So to put a very very long story to bed, pausing a user defined thread, is almost exactly the same as if your called the Thread.sleep() for anywhere in your app, it
pauses the entire application.