Use of Converting User thread -> Daemon thread - java

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.

Related

Who have created these threads?

I am new in Java and I have found one interesting thing. Now I'm learning sockets and while I was debugging my program I noted that there are several Threads which I didn't create. Then I put a breakpoint at the very beginning of my program and when I opened threads I can see all threads that are the part of Socket. But I didn't create it yet, because it was FIRST line of code. I want to now where those threads come from and why they are already created if socket is still not created.
The threads in your screenshot are as follows:
The "main" thread is the thread created to run your main method.
The "Attach Listener" thread is created by the JVM to accept connections to the JVM's debug agent.
The "Common Cleaner" thread is related to the Java 9 Cleaner mechanism which is the better way for doing tidyup on object deletion.
The "Finalizer" thread runs finalize methods on unreachable objects queued by the GC.
The "Reference Handler" thread performs processing on Reference objects queued by the GC.
The "Signal Dispatcher" thread handles native signals (e.g. SIGINT, SIGHUP, etc). Apparently, these need to be handled by a dedicated (native) thread due to the way that signal-related native APIs work.
These threads are all created by the JVM itself.
The JVM also has one or more native GC threads, but apparently they don't show up in the listing. I presume that is because they don't have corresponding Thread object. (They are ... special!)

Daemon thread- Use case

Daemon Threads provide services for user threads, apart from gc What is another example (case) where a daemon thread can be used? (Any task(logic) that can be inside the run() method of a daemon Thread in practice)
Here is a short list of when you may want to use a daemon thread:
Collecting statistics and performing the status monitoring tasks - Sending and receiving network heartbeats, supplying the services to monitoring tools, and so on.
Performing asynchronous I/O tasks - You can create a queue of I/O requests, and set up a group of daemon threads servicing these requests asynchronously.
Listening for incoming connections - daemon threads are very convenient in situations like this, because they let you program a simple "forever" loop, rather than creating a setup that pays attention to exit requests from the main thread.
Sounds like an assignment question ha ha.
You can also use them for IO because IO operation block and its best to do that in a worker thread.
Also network activity if you are waiting for things to download etc. like the response to a post request.
Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.
In short: daemon threads do not keep the program from quitting; user threads keep the program from quitting.

Daemon threads scheduled on an ExecutorService; explain why this is bad form

I'm comfortable with the idea of orderly shutdown on threads scheduled with an ExectuorService; that is to say, calling shutdown or shutdownNow will cause threads created on the pool to exit gracefully. If they respond to interrupt you can be sure finally etc will be called and you'll get a clean, predictable exit (where you can cleanup any resources etc).
However, if you've set your thread to be a daemon (via the executor's ThreadFactory) as below.
ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
#Override
public Thread newThread(Runnable runnable) {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setDaemon(true);
return thread;
}
});
after the main thread terminates, the VM will abruptly terminate any daemon threads. In the example above, a (daemon) thread scheduled and then abruptly terminated will bypass any finally blocks and any interruptable methods won't throw InterruptedException.
So, I tend to think that marking the threads used in a ThreadPoolExecutor's pool as daemon is bad practice... my question is really about helping me vocalise why.
Why is it bad practice (or not if you disagree) to use daemon threads in a ExecutorService's thread pool? In particular I'm interested in describing the life-cycle of the VM shutdown with graceful shutdown (threads that have an interruption policy and play nicely) vs daemon threads.
Expanding that last point, finalize on ThreadPoolExecutor will call shutdown on itself, but when it's using daemon threads, they could have terminated already if finalize was called by the VM. What's the behavior of the thread pool then? Can it be tricked into remaining alive (and so not exiting the VM) if underlying threads terminated abruptly?
Part of the reason I'm asking is because i've seen it used to bypass the need to shutdown the actual ExectorService. Can you think of scenarios where bypassing its shutdown life-cycle can have ill affect? So far, the only reason I can come up with for using daemons is to take a short cut and I want to appreciate any unexpected side affects it could cause.
is it bad practice to use daemon threads in a ExecutorService's thread pool?
If the tasks sent to that particular ExecutorService are ok to be terminated abruptly, then why not, that's what daemon threads do. But generally, there are not many tasks that are ok to be terminated with no shutdown ceremonies at all, so you must know what you're doing if you opt to daemon threads.
finalize() is called when an object is about to be garbage collected. There are no guarantees on when, if ever, any particular object will be GCd, and ThreadPoolExecutor is no exception, so its finalize() may or may not be called. The behavior depends on the particular JRE implementation, and even with the same implementation, may vary from time to time.
Daemon threads can be useful, and if they weren't terminated abruptly, they wouldn't be so useful IMO.
Presumably we could imagine another type of thread, which are interrupted when no normal threads are running anymore, instead of being abruptly terminated. That may be a little convenient, but if you had to do any clean up at all, it's likely that you wanted to do an orderly clean up. This would limit the convenience of this feature.
On the other hand, if you had tasks that would not need any clean up at shutdown, deamon threads are quite convenient. And you wouldn't want to waste time waiting them to arrive at some specific state or risk a hang up on shutdown etc., because the reason you are using a deamon thread is because you don't need any kind of clean up. It would be a waste of time to execute anything if the app. is shutting down. If you care, then you shouldn't have used deamon threads.
It's no different with deamon thread pools. If that thread pool is doing tasks that do not need any clean up at shutdown, then it would make sense because of the convenience.
From the JCiP book:
Daemon threads should be used sparinglyfew processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for "housekeeping" tasks, such as a background thread that periodically removes expired entries from an in-memory cache
I tend to have different pools for daemon and non-daemon threads. Daemon pools tend to do recurring clean up jobs, monitoring and background tasks which don't matter if one or two is not executed. Any task which is only meaningful while the application is still running is good to make a daemon thread task. e.g. GC threads are daemon threads.

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