Daemon Thread is still alive after closing the app - java

I'm just testing with an almost empty android project.
I created a daemon thread in the Main Activity.
Started the app, and pressed the back button on the phone to close the app.
But the daemon thread never dies.
Daemon Thread works really well with an empty JAVA PROJECT.
But with android, doesn't work.
I searched for the solution for hours but only got this.
A daemon thread only runs as long as there are non-daemon threads
running. When the last non-daemon thread ends, the runtime will exit.
This is not normally relevant to applications with a UI.
Does anyone know how to solve this?
PS.
I stopped the app not by pressing the hardware back button but by pressing the 'Force stop' button in 'App info', and both of the app and the thread are gone!
I first learned about Daemon Thread from some example codes for android develoment.
But nobody mentioned about what I've experienced.
Do android developers just believe Daemon Threads will be killed for sure?

But the daemon thread never dies.
Presumably, you did not cancel() the thread. You need to do this at an appropriate point.
But with android, doesn't work.
It works just fine. It works the same as in Java, as you can tell by reading your quoted passage. The difference is in how long your process lives and in the threads in that process (Android processes have other threads besides ones that you fork).
Does anyone know how to solve this?
Call cancel() on your thread at an appropriate point.

Pressing back button does not close the app (assuming that closing means process termination). That only finishes an activity but process is still running.
To achieve desired behavior you can use eg. AsyncTask and call cancel() from appropriate callback of your Activity eg. in onDestroy() or onBackPressed() if you are interested exactly in back button presses.

apologies for pointing possible basic out but follow your problem have you ensured after closing that its not running in you Task Manager (ctrl+alt+delete)..have task manager running alongside your daemon then during the closing of daemon watch what happens during and after closing in task manager as it may be backing up files in accordance with settings-check settings in daemon....or have you used an ExecutorService to run as Daemon in Java in which case this will prevent your program from shutting down see here
ExecutorService - 10 tips and tricks
Java Applicatioin Process Hangs on Windows and Cached Thread Pool

Related

Using existing Thread for Java AWT

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.

Analysing threads through eclipse debug view

If a multi threaded application is running in debug from eclipse then is there any way to know which thread is sleeping or waiting by looking into debug view where all the threads are listed? As I can only see running threads there.
All the threads are shown, the (Running) value just means you have not suspended the thread. You can use the Suspend button to suspend an individual thread or the entire application. When you do this you can expand the entry for the thread in the view and see if it is sleeping, waiting or executing code.
Single suspended thread which is waiting:
You can use JvisualVM to get a graph over time of which threads are running/sleeping. JvisualVM comes with your JDK. If you are looking for a performance issue, it also has a profiler. There is also a plugin for eclipse (which I've never used) that can help with launching it. http://visualvm.java.net/eclipse-launcher.html

Thread restart after computer standby

I have an application running in the Windows system tray and it seem like after I put the computer in stand-by (not shutdown!) when I turn the system back on, a Thread I have running in the application does not continue running. How would I either A) keep the Thread running, or B) determine the system has come back from stand-by and restart the Thread?
You don't need to resume threads after the system resumes. That happens automatically. If your thread or process doesn't resume operation properly it is probably mis-handling the standby or hibernate.
Maybe the application is not 100% thread-safe and/or the thread died by an uncaught exception while the system is going stand-by or back from it. Set up an UncaughtExceptionHandler for your thread which logs the uncaught exceptions to a file.
FindBugs and PMD are also useful for hints.

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.

Categories

Resources