What is AWT-Windows thread? - java

When I am working with AWT, after calling the Toolkit.getDefaultToolkit(), I have printed the current running threads in my program. I would like to know what is that AWT-Windows thread that is running in the background. What does it do and why does it have 6 priority.
Also, the line
Thread[AWT-Windows,6,main]
does the main mean that the thread is started in the main thread?
Thanks in advance.

AWT is the Java Abstract Window Toolkit. The AWT thread should be handling all AWT events, rendering, etc...
The 6 priority is just one above normal priority to make this scheduler bias slightly towards it.
main is the group of the thread.
EDIT
The AWT-Windows thread specifically handles polling events from the native Windows C++ API for GUIs. The specific native method that handles the events is sun.awt.windows.WToolkit.eventLoop().

Related

How is a Java application equipped?

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

Pump events from another thread than the Event Dispatching Thread in Swing

In my application, some process that is started in AWT's Event Dispatching Thread (EDT) may be interrupted under particular circumstances. Then it waits for input from the user. Alas, as the process is located in the EDT, the whole application freezes and the user is unable to relaunch the process, thus creating a deadlock. Is there any way to interrupt the EDT and lauch a new event pump from another thread ? Then the user would be able to interact with the UI.
What I am trying to do looks more or less like opening a modal dialog, except that I don't want a dialog because my component is complex. I'd rather display it right inside my root pane. So I had a look at how it's done in java.awt.Dialog, and had a pretty good understanding of it, but the most important classes that are used (EventDispatchThread, SequencedEvent, ...) are protected and therefore inaccessible for me.
Thank you all for your answers.
I'll be more specific. I am actually working on an application which embeds a homegrown scripting language. I am developing a debugger for this language. The debugger (as all debuggers) would stop the script execution whenever a breakpoint is met. The scripted processes can be triggered from many places (including from the EDT) in the code so taking the the process out of the EDT is not an option. I'd like the debugger UI to be embedded in the application (in a side pane to be precise). So when a breakpoint is met I would need the current thread (possibly the EDT, not to say mainly) to be interrupted and at least the debugger's UI should still be responsive. Also I am developing atop of the JDK 1.4 so no way to use JDK7 alas.
What I am currently doing is opening a JDialog with the debugger embedded. It all works fine but as I said I am not fully satisfied by this solution because I would really want my debugger to be embedded right in my main window.
If you are using JDK7, you can use the SecondaryLoop interface. An instance of this interface can be created through the EventQueue.createSecondaryLoop method
There was an informative blog post with an example but the server seems to be offline for the moment.
A small edit as I am still not fully sure I understand your question.
If you want to wait for user input from a worker thread, you can use the SwingUtilities.invokeAndWait method and use a blocking method (e.g. show a JOptionPane to retrieve user input). Due to the invokeAndWait your worker thread will be stopped until the Runnable on the EDT is processed. If you use a blocking method on the EDT to retrieve the user input that Runnable will only be finished when the user has provided his/her input

How to view everything running on the event thread

We are experiencing a bug we cannot track down where something is freezing up our swing thread (it's been almost 2 weeks now and no real results) - we are experienced Swing programmers but we have a huge program and believe it to be in some of the legacy code
I am wondering, is there any way outside of editing the actual EventQueue class in the JDK which will allow us to view all pieces of our code currently running on the Event Dispatch Thread - maybe some type of tool which will allow us to view things as they enter or leave the event dispatch thread?
One interesting approach is to extend EventQueue and push() it, as shown here.
Logging everything that passes through the Event Dispatch Thread seems a cumbersome way to diagnose a freeze. Wouldn't it be easier to wait until the problem occurs, and then ask the Event Dispatch Thread what it's doing now? One way to do this is to enable JMX monitoring, connect to your running process with a JMX client such a VisualVM (which ships with the JDK), wait for the problem to occur, and then take a thread dump.
In case you still wish to log everything the Event Dispatch Thread is doing, you can do this by:
In Eclipse, launch the application in debug mode.
Create a breakpoint on EventQueue.dispatchEvent, right-click it, select "properties", check "condition", and enter the following "condition":
System.out.println(arg0);
return false;
It might be good idea to try BTrace to instrument the EventQueue and capture stack traces each time something gets added. I think the latest VisualVM has plugins that will allow you to instrument a running JVM with a BTrace script.
If you're using the Oracle JRE, there is a TracedEventQueue included already. You can install it as mentioned before:
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.push(new TracedEventQueue());
Note, this will output a lot of output...

With Swing & Java, what is done by the "Swing-Shell" thread

with threads & swing, the event queue (event dispatch thread) is broadly presented & discussed.
However, when examining the thread states with a Swing application, there's also a thread named Swing-Shell. With brief googling I couldn't find much details, mostly thread stack traces with bug reports etc.
Can somebody describe shortly what that thread does. Or even better, does somebody have some link to some documentations
EDIT: I was asking too fast without enough details, sorry. I was going though various
JFileChooser issues and a thread named "Swing-Shell" occurs there, having
something to do with Windows COM services for file system.
A sample stack trace within a deadlock problem can be found at
Sun Bug #6741890.
(The thread stack trace starts with sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run).
With closer inspection with jconsole, I noticed that the thread isn't present there until
I have used JFileChooser (JFileChooser for example; the Swing-Shell thread will probably be started
by any components using Win32ShellFolderManager)
The thread seems to exist also after the usage of JFileChooser.
So, answering to myself, the thread seems to be a separate thread used for COM services with
file-related operations (with Windows only? ). If somebody can provide more details, welcome =)
The number, purpose and naming of initial threads is implementation dependent. On my platform, the event dispatch thread (EDT) is named AWT-EventQueue-0.
Addendum: The only other reference I found says, "A Motif application uses a shell widget to communicate with the window manager." Are you using a Swing library of some kind?
As suggested above, a thread dump might be illuminating. Recent versions of NetBeans' profiler include a save button; I've attached a snapshot of the threads in a typical busy demo.

Difference between SwingWorker and SwingUtilities.invokeLater

I need to run some method in Swing application in separate thread. What is the difference between using SwingWorker and SwingUtilities.invokeLater. Which one should I use to run a thread in Swing application? I couldn't find exact info in the tutorial at
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html
SwingUtilities.invokeLater is used if you have something that must run in the EDT.
If you have a long-running task, you instead need to use a SwingWorker, since it does not run on the EDT and therefore does not cause the GUI to freeze while it runs.
It looks like you would want to:
use SwingWorker when you need to monitor the status of a long-running background process
use SwingUtilities.invokeLater if you just want a short task to run but do not need feedback on it. Sort of like a fire-and-forget. Just keep in mind it will run in the AWT event dispatching thread, so your application would not be getting any events handled while the task is running.

Categories