How is a Java application equipped? - java

I read below from the book < Core Java vol. 1 >:
Every Java application starts with a main method that runs in the main
thread. In a Swing program, the main thread is short-lived. It
schedules the construction of the user interface in the event dispatch
thread and then exits...Other threads, such as the thread that posts
events into the event queue, are running behind the scenes, but those
threads are invisible to the application programmer.
It gives me a feeling that each Java program is accommodated by the JVM with a standard set of threads. And I think they include:
A main thread
A event dispatch thread
I guess such threads are just like other resources such as heap space, stack that JVM granted to each Java application. And customer should do different work properly in different threads. Such as do Swing-related things only in the event dispatch thread.
Am I correct on this? Where can I find some authoritative reference? The JVM spec seems not have this.
And if I never use the event dispatch thread, such as in a console application, can I disable it to save some CPU cycle?
Add 1
Below link explains the detail about how Swing framework employs threads.
Concurrency in Swing
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

It appears that this is implementation-defined, but HotSpot has the following:
VM thread
This thread waits for operations to appear that require the JVM to reach a safe-point. The reason these operations have to happen on a separate thread is because they all require the JVM to be at a safe point where modifications to the heap can not occur. The type of operations performed by this thread are "stop-the-world" garbage collections, thread stack dumps, thread suspension and biased locking revocation.
Periodic task thread
This thread is responsible for timer events (i.e. interrupts) that are used to schedule execution of periodic operations
GC threads
These threads support the different types of garbage collection activities that occur in the JVM
Compiler threads
These threads compile byte code to native code at runtime
Signal dispatcher thread
This thread receives signals sent to the JVM process and handle them inside the JVM by calling the appropriate JVM methods.
In addition to any threads that your code spawns.
EDIT in response to the bounty (you're right, some guy's blog is pretty shaky support, although it was the best place I could find everything summarized) --- OpenJDK's description of their runtime system (intended to be a copy of HotSpot) describes the same thing:
People are often surprised to discover that even executing a simple “Hello World” program can result in the creation of a dozen or more threads in the system. These arise from a combination of internal VM threads, and library related threads (such as reference handler and finalizer threads). The main kinds of VM threads are as follows:
VM thread: This singleton instance of VMThread is responsible for executing VM operations...
Periodic task thread: This singleton instance of WatcherThread simulates timer interrupts for executing periodic operations within the VM
GC threads: These threads, of different types, support parallel and concurrent garbage collection
Compiler threads: These threads perform runtime compilation of bytecode to native code
Signal dispatcher thread: This thread waits for process directed signals and dispatches them to a Java level signal handling method
I can't find any references from Oracle to confirm that their implementation is the same, but these slides from a presentation by Paul Hohenesee at Sun mentions:
Thread types
Java, aka mutator
One VM thread: GC, deoptimization, etc.
Compiler
Watcher, timer
Low memory monitor
Garbage collector, parallel collectors
Given that this presentation must be at least 6 years old, the implementation may have changed slightly, but the components are more or less the same.

Here is a simple way to print the active threads:
import java.util.Set;
public class ListThreads
{
public static void main(String[] args) throws InterruptedException
{
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet)
System.out.println(thread.getName());
}
}
Apart from your main thread, you will see a couple of other threads:
Attach Listener
Finalizer
Reference Handler
Signal Dispatcher
Sometimes one of these as well:
Monitor Ctrl-Break
DestroyJavaVM
These threads are "daemon threads", which means that they do not stop your java process from exiting, even if they are not finished. So, your "main" thread is the only non-daemon thread.
The Swing event dispatcher thread, is not one of them, and will not be started by default. It will only start once you start using Swing components.
All of these threads are crucial. Just accept their presence. They are good for you.

1) Every swing application is a java application.
But,
2) Not every java application is a swing application.
That said every java application is provided with a main thread by the JVM.
In addition to that every swing application is provided with an event dispatcher thread, due to the swing specification (Java Swing APIs and Developer Guide).
Aslong you don't import APIs you don't require, it won't be necessary to get a headache about stopping unnecessarily started threads.

This is actually a JVM implementation concern, not prescribed by the JVM spec. You can asume that each JVM provides your application with at least 1 thread, the main thread. The Event dispatch thread is Swing specific.
See also the Thread javadoc javadoc .

In addition to other answers : why not try some programs with the a few utilities to print the threads. There is API to enumerate the main and sub thread groups (in effect all). Do this with an app that :
has a main and nothing else
main with a few other methods and objects
main with a class that makes its own thread
main that initializes a swing UI
web app that has a simple jsp test page
Code to see all threads https://stackoverflow.com/a/1323480/1643558 (there are other ways but this one is good to get a understanding and will work fine in most apps I have tried, there is also https://stackoverflow.com/a/3018672/1643558)
FYI a web app could launch a swing ui - though only of use if it does it just for the admin and in a sigleton, as the UI would show on the server. If it made the UI for every user of the app it would quickly run out of memory and be annoying for anyone logged on to the server (assuming the server has UI/ desktop). So not included web app + swing though its possible.

I guess such threads are just like other resources such as heap space, stack that JVM granted to each Java application. And customer should do different work properly in different threads. Such as do Swing-related things only in the event dispatch thread.
The common JVM threads as mentioned by #Patrick are spawned (by the JVM) during runtime initialization before the user program starts execution and perform maintenance/housekeeping jobs in the JVM.
The customer i.e. user threads, spawned from within application code, cannot directly control System level threads. Swing-related threads would start when Swing-related code is executed not for all types of java programs.
Am I correct on this? Where can I find some authoritative reference? The JVM spec seems not have this.
Apart from the links mentioned by #Patrick check the following link:
RuntimeOverview
And if I never use the event dispatch thread, such as in a console application, can I disable it to save some CPU cycle?
The event dispatch thread is created in case a Swing application is executed. You could only control threads created by user application, not the JVM runtime threads.

And if I never use the event dispatch thread, such as in a console application, can I disable it to save some CPU cycle?
Ans: Event dispatch thread isn't initiated unless your java Application is a swing application. So you can safely assume that your java isn't using event dispatch thread
Coming to threads:
Each thread is a process, a program you write can be divided into many processes.
Process can be defined as a program in execution.
Threads are mainly used for parallel programming (Don't confuse with concurrent programming). Also threads can be software defined or Hardware("dynamic" by the processor). The threads which you speak about here are software defined threads and you never care about hardware defined threads. If the processor you use is multi core then different threads may run on different cores or on the same one based on Tomasulo's Algorithm

Related

If thread scheduler runs one thread at a time then how does java provide multi-threading?

Below is what I have seen on java t point about thread scheduler.
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
The source you are quoting sounds somehow outdated. In present day JVM implementations, Java uses underlying operating system threads.
In other words: a Java thread is mapped by the JVM to a thread provided by the operating system. See here for example.
In that sense, the "true" multi-threading capabilities of your system very much depend on the JVM implementation/version and the OS type/version; and even the capabilities of the underlying hardware. But rest assured: on a current day system, Java is able to run many threads in "real parallel".
In your context - Java used "green threads" at some point (and then Java would manage the threads) - but that is computer science history (many many years in the past). See here for example.
Thread scheduler in java is the part of the JVM that decides which thread should run.
Close, but... Most JVMs that anybody uses for real work in the last couple of decades use "native threading". That means, that scheduling is the operating system's job. The JVM does not get involved.
There is no guarantee [of] which runnable thread will [next] be chosen to run by the thread scheduler.
True but..., The operating system implements a thread scheduling policy (It may be capable of implementing any of several policies, to be chosen by the system administrator). If you understand the policy, then you could, in principle, know which thread will be scheduled next.
But true, because the Java Language Specification does not say anything about thread scheduling policies, and if you're writing a "run anywhere" Java program, then you should not depend on any particular policy.
Only one thread at a time can run in a single process.
False, but... It was true, maybe thirty years ago. Virtually all computers, tablets, and cell phones these days have more than one processor. At any given instant, there can be one thread running on each processor.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Yes. The thread scheduler on any given OS doesn't mainly do whatever, it implements a policy. On most computers, tablets, and cell phones the policy choices all will be preemptive. That means that a thread could be be de-scheduled at any point in time (e.g., half way through an i++; statement).
The alternative to preemptive multi-tasking is called cooperative multitasking, in which a thread can lose its turn on the processor only at certain, well defined yield points. That's what Thread.yield() is for, but I don't know where you are ever going to find Java running in a cooperative multitasking environment.
You can run more than one thread in a process at the same time if your machine supports that.
Information you have is very obsolete. What you describe was valid for OS when each process was effectviely a single thread (Windows 3.1, or OLD unix kernels, Macintosh system 7). That time JVM running as a single process had to implement its own thread scheduler and thread management.
Today all common platforms support natively multithreading and by default JVM uses the underlying system implementation

What is the default number of threads running in the JVM?

Recently I've been learning more about thread and I was wondering why the resource monitor shows always 19 threads running for the Java process.
Now my questions are:
Is this the VM using 19 threads?
If so:
Are you able to access those threads?
Is it possible to use these threads for thread pooling?
Is it possible to decrease the amount of threads?
If not:
What is causing to show up the 19 threads?
I created a small .jar (see bottom for source) that would run and create a fixed threadpool of 5 worker threads. To that pool I sent tasks and I noticed that after all tasks have been handled, the amount of threads java uses goes back to 19.
Are the threads in the fixed threadpool idle or have they been removed and thus new threads are being created whenever new tasks are submitted?
Sorry for the multiple questions in one post.
Link to source: http://pastebin.com/iXpLbFVF
Image while sending tasks: http://gyazo.com/223d720bf73c1b919fbfe0b69088838a
Image after sending tasks: http://gyazo.com/3147269d90eb2c916373220ef53c0b92
It depends on the JVM version, the JVM vendor and some settings like which garbage collector is in place (and how the GC is tuned). Also some add-ons like agents or JMX can change the system running threads. And of course all threads started by the actual Java program. You can use the jstack program to actually list them (most of the system threads have obvious names). They include threads for finalisation, GC, the main thread, the Gui threads (if used), also JIT Compiler Threads and reference weakeners.

What happens if I call a java function from multiple threads from C with JNI?

This link seems to suggest that "it just works": (pretty far on the bottom under 7.3 Attaching Native Threads) http://java.sun.com/docs/books/jni/html/invoke.html
I don't see how that is possible, is the embedded JVM going to start its own threads automatically? Or queue the JNI calls? How else could there be multiple calls to the same virtual machine. which I haven't instructed to do any threading?
Any way I can imagine that to work is, if the java code will simply be executed in the same calling thread as the c code. Is that correct? That would mean that I don't have to do any threading in Java.
The jvm does not have to create its own threads, the method calls are executed on the native threads that make them. The AttachCurrentThread and DetachCurrentThread will take care of any necessary jvm internal state management, for example creating java Thread objects wrapping the native threads.
The JVM starts its own threads which it needs to run. You trigger this thread creation by starting the JVM.

Why need use non-daemon threads in java?

It seems that daemon threads are always better - because they will be stopped by the VM after application main thread exits. Are there any other reasons to use non-daemon threads besides the cases when it is not possible to interrupt some operation ?
Thanks.
When you are writing a server (e.g. a servlet container), all your main has to do is to bootstrap and start HTTP listener threads, accepting threads, file system scanning threads, RMI threads, etc.
After bootstrap is done, main is no longer needed as everything happens asynchronously. In this case all essential threads are non-daemon as they have to live past the main method.
Even in Swing (desktop programming) the only requirement on main is to initialize the main window (JFrame). The rest happens in Swing listener threads (EDT) and various background threads.
In fact, any thread that should finish naturally (leaving its "run" method) should not be a daemon thread, as you don't want the JVM to terminate while they are doing their job.
This applies to every thread that you launch, and that you expect to terminate naturally.
As a rule of thumb, daemon threads are the exception, not the rule.
The one major difference is in how daemon threads exit; the JVM just stops them.
finally blocks are not executed
stacks are not unwound
You do not want to use daemon threads for things that need to be left in a known state such as file i/o, database transactions, etc.
You use non-daemon thread whenever you are doing something which you don't want to stop because an another thread exits. If the only purpose of a thread is to support other threads, then it makes sense to use a daemon thread.
If you want to exit when the main thread exits you can call System.exit(). Many applications don't keep their main thread and all the work is in threads it starts.
The VM may stop daemon threads in the middle of their executions, and persistent data could be corrupted because of that.
If you need more control of when a thread is safe to die, do not make it a daemon.

A question about Thread and Process

I read some tutorial about threads and processes, it is said that the processes be scheduled by operating system kernel, and the threads can be managed and scheduled in a user mode.
I do not understand the saying "threads can be managed and scheduled in a user mode",
for example: the producer and consumer problem? is this a example for "scheduled in a user mode"? or can anyone explain me?
Not sure what tutorial you're looking at, but there are two ways that threads can be scheduled.
The first is user-mode scheduling, which basically mean that one process, using Green threads or perhaps fibers, schedules different threads to run without involving the operating system in its decision. This can be more portable across operating systems, but usually doesn't allow you to take advantage of multiple processors.
The second is kernel scheduling, which means that the various threads are visible to the kernel and are scheduled by it, possibly simultaneously on different processors. This can make thread creation and scheduling more expensive, however.
So it doesn't really depend on the problem that you are trying to solve. User-mode just means that the scheduling of threads happens without involving the operating system. Some early Java versions used Green/user-mode threads, but I believe most now use native/kernel threads.
EDIT:
Coding Horror has a nice overview of the difference between user and kernel mode.
Get a better tutorial? The official Java tutorials are quite good, and contain a lesson on concurrency, that also defines what process and thread mean.
PS: Whether threads are managed/scheduled in user mode is an implementation detail of the Java Virtual Machine that generally need not concern the application programmer.
Scheduled in user mode means you have control over the threads of your software but they are managed by the operating system kernel. So yes, the producer consumer problem is an example you normally handle yourself (but it is not directly related to user mode scheduling) by having two threads, a producer thread and a consumer thread. Both threads access the same shared recource. This resource has to be thread-safe, this means you have to make sure the shared resource does not get corrupted becouse both threads access it at the same time. Thread safety can either be guaranteed by using thread-safe data types or by manually locking or synchronizing your resource.
However, even if you have some control over your threads e.g. starting threads, stopping threads, make threads sleep etc. you do not have full control. The operating system is still managing which threads are allowed cpu time etc.

Categories