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!)
Related
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.
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 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.
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
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.