Is garbage collector a daemon (background) thread?
Thanks.
I will assume yes, Garbage collector thread is a daemon thread. Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation or other requests for the java runtime system.
It's not a thread from a java.lang.Thread perspective at least.
Yes: http://www.javaperspective.com/daemon-threads.html :
(Daemon threads are considered as threads that run in the background and they are generally used as service providers for user threads. For example, the Java garbage collector is a daemon thread)
on jdk 1.8 following threads are listed with
ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();
for(long id:mxbean.getAllThreadIds())
System.out.println(mxbean.getThreadInfo(id));
Output -
"Attach Listener" Id=5 RUNNABLE
"Signal Dispatcher" Id=4 RUNNABLE
"Finalizer" Id=3 WAITING on java.lang.ref.ReferenceQueue$Lock#63947c6b
"Reference Handler" Id=2 WAITING on java.lang.ref.Reference$Lock#2b193f2d
"main" Id=1 RUNNABLE
There is no GC thread. It can safely be said garbage collection process is native.
A daemon thread is also a thread that continues to run even after the JVM exits. From Oracle documentation
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 GC is a daemon thread, it should be a native thread spawned by the java run time, but can continue to run after he JVM exits
Related
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!)
As per my knowledge main() in Java is a non daemon thread by default, so is it possible to convert it into a daemon thread?
If there are only daemon threads running then the JVM will shutdown. If the main thread was a daemon thread then the program couldn't run without shutting down right away. Also you're not allowed to set the daemon property on a thread after it's started, you can't change a non-daemon thread to a daemon thread while it's running:
public final void setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread. The Java
Virtual Machine exits when the only threads running are all daemon
threads.
This method must be invoked before the thread is started.
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.
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.
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.