Swing and Threads - java

I have a Swing interface, when I click on a button a thread is created at infinity (the genus while(true)...).
My question is: when I close the main process, will the created threads be closed automatically?

Depends on if the threads you've started are daemon threads or not, and how you close the main process.
Here's the relevant documentation from the standard library:
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, if you shut down the main process by System.exit or by using jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) then all threads will die when you shut down.
If you simply let the main thread (the thread running public static void main) drop off the edge of the main method, then the threads will continue to run.

Yes, as long as it's not set up as a daemon thread. You can view instrumented JVM's using the jps tool:
jps -l

Related

JavaFx execution can not finish until the stop method of the Application class has not returned?

I learned that the stop method of the Application class of the
JavaFX application is called when it is about to terminate.
Does it mean that all the threads of my application continues to execute until the stop method has not returned?
So the termination of my application’s threads start meanwhile the execution of the stop method, or the termination of the threads start only after the stop method finished execution?
From docs here.
This method is called on the JavaFX Application Thread.
So if you have other threads performing their own tasks. Its your responsibility to handle them.
When you call close() on your primaryStage JavaFX calls the handler assigned to setOnCloseRequest() if you have override it before it will execute your code then closes the main Thread
If you have any other threads that are still running you have to close it yourself unless they are daemon threads as they close with the app anyway or call System.exit(0) your app will force close all the threads opened by your app
If you want I can provide an example that demonstrate my words

How to protect a program from losing data if it is interrupted?

Blockquote
I have a Java program with functionality that needs to be run periodically. However, I would like to be able to close the wrapper program (if you're a UNIX person, think Ctrl+C in the terminal window or SIGTERM) without any risk of interrupting the main program processes or threads that the wrapper would start.
At first I was thinking I should have my main program sleep for a certain interval after each round of processing. Then I figured that if the program needs to be closed and is manually interrupted by the user, it might be interrupted while it was processing data and the output files would be chopped or corrupted.
I'm thinking the best way is to write a wrapper program (probably also in Java) that would invoke the main program. If something closes the wrapper, I would like the spawned threads or program instances of my main program to remain open until they are ready to close properly. In addition, at most one instance of the main program should be running at any time.
Here's what I would like my wrapper to do (in pseudocode):
Every n minutes:
If an instance of the main program is running, do nothing
else spawn an instance of the main program.
On Close:
leave main program run to completion if it is running
Should I use the Java Runtime object/library to run my main program (effectively from the command line) or should I change my main program to implement Runnable and have the wrapper program spawn threads running my main program?
EDIT (possible solution?):
Currently I'm thinking of using the Java Runtime object to invoke the main program using the exec function (see http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html and http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html). To determine if the main program is already running I can just use the Process.exitValue() function. If it throws an IllegalThreadStateException then the main program is still running.
You can use a shutdown hook to perform an orderly shutdown when your application gets a SIGINT (Control-C): see Runtime.addShutdownHook(...).
However this doesn't deal with SIGKILL, JVM crashes, operating system crashes and hard power failures. Indeed, there is no way that an application can shut down cleanly in that kind of scenario. For that you need to design your application to periodically persist its state, using a robust persistence mechanism.
Create a new thread that has certain flags set in a static way. this thread will be run at the start of the main application, could be run/loaded from it.
Create a java event listener on the closing action of the program and regster your new thread in it. Whenever your program is closed this new thread will initiate other threads to come alive and do the final savings of the resources to perform one of the stated conditions above. your new process now will kill these threads one after another(whenever each on has done is job) until all the above conditions (flags) are met. when there is no other thread left, this new thread will kill itself, and the program is finished.

Why need use non-daemon threads in java?

It seems that daemon threads are always better - because they will be stopped by the VM after application main thread exits. Are there any other reasons to use non-daemon threads besides the cases when it is not possible to interrupt some operation ?
Thanks.
When you are writing a server (e.g. a servlet container), all your main has to do is to bootstrap and start HTTP listener threads, accepting threads, file system scanning threads, RMI threads, etc.
After bootstrap is done, main is no longer needed as everything happens asynchronously. In this case all essential threads are non-daemon as they have to live past the main method.
Even in Swing (desktop programming) the only requirement on main is to initialize the main window (JFrame). The rest happens in Swing listener threads (EDT) and various background threads.
In fact, any thread that should finish naturally (leaving its "run" method) should not be a daemon thread, as you don't want the JVM to terminate while they are doing their job.
This applies to every thread that you launch, and that you expect to terminate naturally.
As a rule of thumb, daemon threads are the exception, not the rule.
The one major difference is in how daemon threads exit; the JVM just stops them.
finally blocks are not executed
stacks are not unwound
You do not want to use daemon threads for things that need to be left in a known state such as file i/o, database transactions, etc.
You use non-daemon thread whenever you are doing something which you don't want to stop because an another thread exits. If the only purpose of a thread is to support other threads, then it makes sense to use a daemon thread.
If you want to exit when the main thread exits you can call System.exit(). Many applications don't keep their main thread and all the work is in threads it starts.
The VM may stop daemon threads in the middle of their executions, and persistent data could be corrupted because of that.
If you need more control of when a thread is safe to die, do not make it a daemon.

determine if an application is shutting down normally

is there a way to determing if a jvm is shutting down normally? Shutdown hook can only spawn a thread, is there a way to determine if the JVM is existing normally or abnormally at that time?
You could write a file on startup and delete it again on graceful exit. If the JVM is gone but the file is still there you know that it crashed or has otherwise exited in a unintended manner.
I remembered a similar question being asked time ago. One possible course of action is the use of SignalHandler.
You can read the full article here. It appears to be related to IBM JVM but I think it is equally valid for Java Hotspot.
A little-known feature of Java is the
ability of an application to install
its own signal handler, which is
supported through the sun.misc.Signal
class. However, use caution when using
classes from the sun.misc package
because it contains undocumented
support classes that may change
between releases of Java. You can
install a Java handler for any signal
that is not used by the JVM. These
signal handlers are similar to native
handlers because they're invoked when
a native system signal is raised, but
they will always run as a separate
Java thread. Essentially, when a
signal is raised for which a Java
signal handler is available, the JVM's
"signal dispatcher thread" is woken up
and informed of the signal. The signal
dispatcher thread then invokes a Java
method to create and start a new
thread for the installed Java signal
handler. To write a Java signal
handler, define a class that
implements the sun.misc.SignalHandler
interface and register the handler by
using the sun.misc.Signal.handle()
method.
Check return sttaus using command $?
When the JVM is shutting down normally, this means that the main thread has ended. If the JVM is shutting down for some other resaon (e.g. the user pressed Strg+C), the main thread is still running. So you can store a reference to the main thread in your shutdown hook and check whether this thread is still alive. Of course this assumes that the main thread will normally be the last running thread in your application. I don't know how the situation is if one of the threads called System.exit(), but you could easily find this out.

Java app lifecycle

When does a typical Java app finish?
If I start a new thread in the main method and then the main method finishes, but the other thread continues working, the app would still be on until all it's threads have died, wouldn't it?
Thanks & Merry Christmas!
Yes, unless it's a deamon thread. Quoting from Thread API:
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.
The main() function defines your main user thread. You might have other user threads that you created as well. You might also have called setDeamon() on some of those threads.
The JVM will end when:
The main routine ends and there are no other non-deamon threads
You have an uncaught Exception in the main thread and there are no other non-deamon threads
System.exit() or Runtime.halt() is called
Internal JVM error (rare)
Kill -9 signal from OS
Power failure or similar non-recoverable hardware failure

Categories