Using existing Thread for Java AWT - java

Is there a way to use a existing Thread (especially the main Thread) for AWT windows. I am currently opening a Frame which then handles everything and the main Thread is just paused and waits for the window to close. For me this seems like a (not very devastating) waste of resources, so I would appreciate only using the main Thread for AWT. Is there a good reason why this isn't done and if not, is there a way to do it?

Just let the main thread exit, there is no need to keep it paused and waiting around.
Threads can be marked as Daemon or not. The application only exits when every non-daemon thread has exited, in Java the Main thread doesn't really have any special significance beyond the fact it is started first.
The EDT thread is not a Daemon thread so it will keep the application alive by itself.
What is Daemon thread in Java?

Based on this documentation http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html
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.
moral of the story :
A Java program will wait for all non-daemon threads to finish first.
In your case you might wanna exit the main thread.

One paused thread (if it's even actually paused) isn't really a big deal. I suggest looking at your program in something like JProfiler, you'll be shocked at what's going on in the background.

Related

JNI - Java exits before native threads finish executing

I'm in the early stages of developing an API in C++, which I'm wrapping in Java using JNI. The native code creates a socket listener thread using WinAPI which should run indefinitely, thereby keeping the program open indefinitely (tested and works fine).
However, when I try to invoke this code in Java, the JVM still terminates when it reaches the end of main, ignoring the running thread. A little research has hinted that Java might think the thread is a daemon rather than a "user thread". But if that's the case, then I can't quite figure out how to convince Java that it actually is a user thread.
Does anyone have a clue about this?
You need to call AttachCurrentThread() for all your native threads, to ensure Java knows about them, so it will wait for them to finish.
Windows doesn't have daemon threads. The process exits when ExitProcess() is called or when the initial thread returns from the application's main function. (In principle, it will also exit if the last thread exits, but that can't be relied upon because Windows may create threads in your process that you don't know about.)
The Java runtime presumably waits for all of its own threads to exit (except for those that it considers daemon threads) before exiting the process. But your threads were created directly via the Win32 API, so Java doesn't know about them and therefore won't wait for them.
If your API wants to continue performing some task beyond the natural lifetime of the calling process, it should probably create a child process rather than a thread. (Or, if the API is Java-specific, it can presumably make use of JNI to ask that Java create the thread on its behalf, or to register the thread with Java.)

Should threads have special design to be shutdown gracefully by Tomcat?

I have developed a multithreaded web application that runs in Tomcat.
But I cannot use
shutdown.bat
Tomcat didn't stop gracefully. In the debugger I saw that threads continue to run after shutdown command. Do I have to fix my application code to meet special requirements ?
Thanks.
... and to tie the other responses to the workings of Java Servlet environments;
if you don't declare your threads as daemon threads, the way to signal the server shutdown to the threads is to implement a ServletContextListener and configure it to your web application (web.xml). When Tomcat is shutting down, it will first shut down each application, which in turn will cause contextDestroyed() method of the listener to be called - and this is where you can signal your own threads that they should finish their work.
Any threads that are still running will keep the Java (Tomcat) process alive. Make sure all your threads exit. Once your threads exit, Tomcat will be able to shut down.
See the javadoc for Thread. Note the following:
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.
You need to cancel your threads, preferably by calling interrupt on them and making sure they are written in such a way that they respond to the interruption -- meaning, checking their interrupted flag and responding intelligently to InterruptedExceptions (not just eating them and continuing on).
The above advice assumes you don't want your threads to drop what they're doing immediately. If you are ok with that then make them daemons.

When are daemon threads useful?

I know that Deamon threads background threads. We can create our own daemon thread by calling setDaemon(true).
My question is: why and when do we need to create our thread as daemon thread?
The JVM exits when all the running threads are daemon threads. So imagine you're writing a simple game where your main method loops until you decide to quit. And imagine that at the start of the game, you start a thread that will endlessly poll some website to trigger alerts. You would like the JVM to exit when you decide to end the game. You don't want the endless polling to prevent the game from ending. So you make this polling thread a daemon thread.
A Deamon thread is automatically terminated by the JVM when all "normal" threads are terminated. Normal threads are never automatically terminated.
Services that you wish to offer to your consumers without any user-interation by way of essentially user-threads form the primary use-case for setting a user thread as a daemon.
As a consequence, until user-threads exist JVM gurantees that daemon threads run continously. You can find examples like GC, UI Thread etc.. those are daemons.
Hope it helps.
As other have pointed, a daemon thread does not prevent the JVM from exiting when the program finishes when this thread is still running.
In general you'd rather not create daemon threads, unless you are absolutely certain the thread has no side effects. Since you can't tell when the thread stops, finalizer blocks are not run, nor are any stack unwound. So try avoiding using IO operations in daemon threads because it can corrupt data.
Normally program terminates when all its threads exited their run() method. Daemon threads do not prevent program to terminate even if they are still running, i.e. executing run().
So, you should use daemon thread if you wish not to prevent program termination when the thread is still running. It is typical for example for long-time periodic tasks but actually depend very much on your program, your design and your taste.
Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound – JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.
I used them with Timer to delete files that cannot be deleted immediately. That is, I generate .exe files, run and then delete them. But there is 50% chance that executable.delete fails, seemingly because image is still blocked by the process in termination. You can reliably delete executable image only after process has finished completely. But, you never know how long it takes. You set .deleteOnExit therefore instead of .delete. But, you do not want to wait until java machine terminates also. It can take very long and you do not want millions of useless stupid .exe files, that you do not need anymore, hanging in the file system. You therefore schedule executable.delete in the timer to happen one-two seconds later. The timer however cannot be usual thread. If it is so, it will block your program from terminating even if there are no files to delete. I can easily make it daemon however because whether my files are deleted or not by timer is immaterial -- the files will be removed either way: either by daemon or java exit. I think it is perfect use of daemon.

Java kills daemon threads in applet reloads

I know that all daemon threads are supposed to be killed when no other non-daemon thread is alive.
I am developping applet which gets data from static objects. Those static objects are downloading some data from remote server in daemon thread. Several applets can access the same data so there is no sense in running thread for every applet.
Problem is when I reload page. Applets are reloading and they registers in those static objects and everything would be just fine except that then JVM kills daemon threads.
Maybe I explain step by step:
Applet is loading and it registers in static object which provides data.
Static object starts daemon thread.
Page reload.
Applet is beeing unloaded (stop() and destroy() are called)
New applet instance is beeing created and it registers in static object.
JVM throws ThreadDeath in daemon thread and communication stops.
In my mind, step 6 should be after 4 and before 5.
Am I missing something?
The workaround I developed is to sleep some time before registering in static object to let JVM kill daemons and then daemon is automaticaly created but it is only a workaround. Is there a some better solution?
Why don't you terminate the daemon thread in stop() or destroy() to make things more clear.
I would not encourage sharing background threads between applets, but if you insist, well you can do the following:
You can catch ThreadDeath by overriding Thread.setDefaultUncaughtExceptionHandler to be sure not to miss it.
You can then relaunch a new deamon thread from that handler to replace the killed one.
You should ensure you don't use synchronized on shared members in background threads, since your thread can be stopped while in the middle of a synchronized block, as documented by Thread.stop (the Java plugin uses Thread.stop to kill your threads).
Note that if you have at least 2 applets opened in 2 different tabs, reloading one does not make the JVM kill your thread.
The daemon flag does not seem to have any effect in applet environment.

Use of Converting User thread -> Daemon thread

I read, daemon threads are used and controlled by JVM. JVM creates them and also looks after their termination.User threads are controlled by user.
It is also said, we can convert a user thread to daemon thread by calling setDaemon() method.
But, what is the use of such conversion ? Does JVM takes the control of user thread once it has become a dameon thread ?
Let me know if I missed something.
Thanks.
I believe that user and daemon threads are always under the JVM's control. (If that wasn't the case, who would be in charge?)
Here's the distinction (from http://www.xyzws.com/javafaq/what-is-difference-between-user-and-daemon-thread-in-java/196):
The difference between these two types
of threads is straightforward: If the
Java runtime determines that the only
threads running in an application are
daemon threads (i.e., there are no
user threads in existence) the Java
runtime promptly closes down the
application, effectively stopping all
daemon threads dead in their tracks.
In order for an application to
continue running, it must always have
at least one live user thread. In all
other respects the Java runtime treats
daemon threads and user threads in
exactly the same manner.
Daemon threads don't prevent the application from shutting down while they're still doing work. They're more for tasks that need to be done while the app is alive, but are safe to kill off otherwise.

Categories

Resources