In swing for painting is separte thread from event-dispatching thread

hi,
event -dispatching thread is diffenent from paint thread in swing ???

I don't believe so... or if it is, they have a special relationship tieing them together.
why?

Similar Messages

  • ..this method should be invoked from the event-dispatching thread?

    I see this (the title that is) in every single Java demo/example program on this (Sun's) site. However, I just tend to
    public static void main(String[] args){
       new whateverTheClassIsCalled();
    }And I've seen this approach on other sites and other example programs.
    So what exactly is better about this;
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        }where createAndShowGUI() sets and packs the frame. I just do all this in the class constructor (when it's a JFrame!)
    So what does all this thread dispatching stuff mean, why should I use it etc etc.
    tia.

    Is it just me? For some reason it rubs me the wrong way that swing isn't thread safe. From what I've read, my understanding is that its safe to modify swing components from other threads as long as they haven't asked to be painted. If you don't do paint(), pack() or setVisible(true) until the end of your initialization, you will be safe.
    The reason for not being thread safe is almost certainly performance. Swing is slow enough as it is. Since the vast majority of Swing activity takes place in response to events and thus is on the EDT, there usually isn't a problem.
    This is a serious nuisance in network and database programs where multiple threads are used. I end up using invokeLater a lot in those cases, but never for initialization. Sun has only started to recomment that recently.
    Note that the fireXXX methods do not put the event on the EDT, these simply create Event objects and send them to Listeners. If they are executed off the EDT the Listeners will get called off the EDT.

  • Calling a delegate on the UI thread from a work thread inside a child class.

    Hi All,
    I've run into a snag developing a WPF multithreaded app where I need to call a method on the UI thread from my work thread, where the work thread is running a different class.
    Currently I am trying to use a delegate and an event in the 2nd class to call a method in the 1st class on the UI thread. This so far is not working as because the 2nd class is running in its own thread, it causes a runtime error when attempting to call
    the event.
    I've seen lots of solutions referring to using the dispatcher to solve this by invoking the code, however my work thread is running a different class than my UI thread, so it seems the dispatcher is not available?
    Below is as simplified an example as I can make of what I am trying to achieve. Currently the below code results in a "The calling thread cannot access this object because a different thread owns it." exception at runtime.
    The XAML side of this just produces a button connected to startThread2_Click() and a label which is then intended to be updated by the 2nd thread calling the updateLabelThreaded() function in the first thread when the button is clicked.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Threading;
    using System.Threading;
    namespace multithreadtest
    public delegate void runInParent();
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    threadUpdateLabel.Content = "Thread 1";
    private void startThread2_Click(object sender, RoutedEventArgs e)
    thread2Class _Thread2 = new thread2Class();
    _Thread2.runInParentEvent += new runInParent(updateLabelThreaded);
    Thread thread = new Thread(new ThreadStart(_Thread2.threadedTestFunction));
    thread.Start();
    public void updateLabelThreaded()
    threadUpdateLabel.Content = "Thread 2 called me!";
    public class thread2Class
    public event runInParent runInParentEvent;
    public void threadedTestFunction()
    if (runInParentEvent != null)
    runInParentEvent();
    I'm unfortunately not very experienced with c# so I may well be going the complete wrong way about what I'm trying to do. In the larger application I am writing, fundamentally I just need to be able to call a codeblock in the UI thread when I'm in a different
    class on another thread (I am updating many different items on the UI thread when the work thread has performed certain steps, so ideally I want to keep as much UI code as possible out of the work thread. The work threads logic is also rather complicated as
    I am working with both a webAPI and a MySQL server, so keeping it all in its own class would be ideal)
    If a more thorough explanation of what I am trying to achieve would help please let me know.
    Any help with either solving the above problem, or suggestions for alternative ways I could get the class in the UI thread to do something when prompted by the 2nd class in the 2nd thread would be appreciated.
    Thanks :)

    If I follow the explanation, I think you can use MVVM Light messenger.
    You can install it using NuGet.
    Search on mvvm light libraries only.
    You right click solution in solution explorer and choose manage nugget...
    So long as you're not accessing ui stuff on these other threads.
    using GalaSoft.MvvmLight.Messaging;
    namespace wpf_Tester
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    Messenger.Default.Register<String>(this, (action) => ReceiveString(action));
    private void ReceiveString(string msg)
    MessageBox.Show(msg);
    Dispatcher.BeginInvoke((Action)delegate()
    tb.Text = msg;
    private void Button_Click(object sender, RoutedEventArgs e)
    Task.Factory.StartNew(() => {
    Messenger.Default.Send<String>("Hello World");
    What the above does is start up a new thread - that startnew does that.
    It sends of message of type string which the main window has subscribed to....it gets that and puts up a message box.
    The message is sent from the window to the window in that but this will work across any classes in a solution.
    Note that the receive acts on whichever thread the message is sent from.
    I would usually be altering properties of a viewmodel with such code which have no thread affinity.
    If you're then going to directly access properties of ui elements then you need to use Dispatcher.BeginInvoke to get back to the UI thread.
    I do that with an anonymous action in that bit of code but you can call a method or whatever instead if your logic is more complicated or you need it to be re-usable.
    http://social.technet.microsoft.com/wiki/contents/articles/26070.aspx
    Hope that helps.
    Technet articles: Uneventful MVVM;
    All my Technet Articles

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

  • Not Running on the Event Dispatch thread, but UI still freezes

    The environment: I am currently working on an application that requires some heavy lifting in response to user input on a UI. To do this I am using a version of SwingWorker that was backported from java 1.6 to java 1.5 in conjunction with a slew of custom threads.
    The problem: I am currently running into an issue where I am not operating on the Event Dispatch thread (checked by doing a javax.swing.SwingUtilities.isEventDispatchThread()) but the UI is still freezing during this section. The operation involves a loop with about 2000 iterations and contains several file accesses. I have thought about how to make a new thread to perform the same operation, but I do not see how it would be any different since as it is I am not on the EDT. The call is being made from doInBackground and specifically the piece that is slowing things down is the File Accesses (2 for every iteration of the loop). At this point I am not sure how to go about resolving the issue. Any one have any suggestions?

    I am not operating on the Event Dispatch threadThat is the problem. Use multiple threads for GUI, which should delegates to the EDT, and your app logic.

  • Event Dispatch Thread Hangs, what is wrong?

    The Event Dispatch Thread Hangs when showing a modal dialog while running a
    SwingWorker Thread.
    I have included my code at the bottom of the page. There are three classes. I have posted a bug report to red hat. But I want to make sure my code is correct.
    My test case just puts the SwingWorker to sleep
    but the problem occurs if I do something real, like connect to a database, etc.
    Also I have tried little different variations of the logic calling
    setVisible(true)/(false) in different places and the same problem occurs.
    It seems to work with Sun JDK, note I am using IcedTea with Fedora Core 8.
    Version-Release number of selected component (if applicable):
    [szakrews@tuxtel ~]$ java -version
    java version "1.7.0"
    IcedTea Runtime Environment (build 1.7.0-b21)
    IcedTea Client VM (build 1.7.0-b21, mixed mode)How reproducible:
    Every couple times.
    javac TestClass2
    java TestClass2eventually it will hang. If it doesn't try again.
    You don't have to wait for the program to finish either.
    The program runs the Dialog 10 times but it never works or fails in the middle, it will either work or fail from the first dialog displayed.
    I have included a thread dump. That is about the most informative information I can get. Neither tracing nor writing a custom ThreadQueue or Drawing Manager to trace events produces any helpful information.
    Actual results:
    The JProccessBar won't move, and the SwingWorker finishes but the done() method is never run. The PROGRAM is not hung however because if I close the dialog then it will continue.
    Expected results:
    The JProccessBar should always move and the SwingWorker should always run the done() method.
    Additional info:
    java thread dump after freeze, taken with kill -s SIGQUIT <pid>
    2008-06-25 12:25:50
    Full thread dump IcedTea Client VM (1.7.0-b21 mixed mode):
    "DestroyJavaVM" prio=10 tid=0x938afc00 nid=0x1419 waiting on condition
    [0x00000000..0x0018a074]
       java.lang.Thread.State: RUNNABLE
    "AWT-EventQueue-0" prio=10 tid=0x938ae400 nid=0x1429 in Object.wait()
    [0x07f96000..0x07f96f04]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96748f80> (a java.awt.EventQueue)
            at java.lang.Object.wait(Object.java:503)
            at java.awt.EventQueue.getNextEvent(EventQueue.java:485)
            - locked <0x96748f80> (a java.awt.EventQueue)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:248)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:195)
            at java.awt.Dialog$1.run(Dialog.java:1073)
            at java.awt.Dialog$3.run(Dialog.java:1127)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1125)
            at java.awt.Component.show(Component.java:1456)
            at java.awt.Component.setVisible(Component.java:1408)
            at java.awt.Window.setVisible(Window.java:871)
            at java.awt.Dialog.setVisible(Dialog.java:1012)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:72)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:102)
            at TestClass2.showWait(TestClass2.java:79)
            at TestClass2.createAndShowGUI(TestClass2.java:126)
            at TestClass2.access$0(TestClass2.java:114)
            at TestClass2$3.run(TestClass2.java:138)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:227)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:603)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:276)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:191)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:186)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:178)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:139)
    "AWT-Shutdown" prio=10 tid=0x938ad000 nid=0x1428 in Object.wait()
    [0x03ea7000..0x03ea7f84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96749268> (a java.lang.Object)
            at java.lang.Object.wait(Object.java:503)
            at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:281)
            - locked <0x96749268> (a java.lang.Object)
            at java.lang.Thread.run(Thread.java:675)
    "AWT-XAWT" daemon prio=10 tid=0x938a8400 nid=0x1423 runnable
    [0x02ccc000..0x02ccd104]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.X11.XToolkit.waitForEvents(Native Method)
            at sun.awt.X11.XToolkit.run(XToolkit.java:550)
            at sun.awt.X11.XToolkit.run(XToolkit.java:525)
            at java.lang.Thread.run(Thread.java:675)
    "Java2D Disposer" daemon prio=10 tid=0x93854000 nid=0x1421 in Object.wait()
    [0x07aea000..0x07aead84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at sun.java2d.Disposer.run(Disposer.java:143)
            at java.lang.Thread.run(Thread.java:675)
    "Low Memory Detector" daemon prio=10 tid=0x93c15000 nid=0x141f runnable
    [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x93c13400 nid=0x141e waiting on condition
    [0x00000000..0x03a8a954]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x93c11c00 nid=0x141d waiting on
    condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=10 tid=0x095e7000 nid=0x141c in Object.wait()
    [0x005d2000..0x005d3004]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
    "Reference Handler" daemon prio=10 tid=0x095e2400 nid=0x141b in Object.wait()
    [0x00581000..0x00582084]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7260> (a java.lang.ref.Reference$Lock)
            at java.lang.Object.wait(Object.java:503)
            at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:134)
            - locked <0x966e7260> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x095dec00 nid=0x141a runnable
    "VM Periodic Task Thread" prio=10 tid=0x93c17400 nid=0x1420 waiting on condition
    JNI global references: 836
    Heap
    def new generation   total 960K, used 152K [0x93f40000, 0x94040000, 0x966a0000)
      eden space 896K,   9% used [0x93f40000, 0x93f56148, 0x94020000)
      from space 64K, 100% used [0x94020000, 0x94030000, 0x94030000)
      to   space 64K,   0% used [0x94030000, 0x94030000, 0x94040000)
    tenured generation   total 4096K, used 1088K [0x966a0000, 0x96aa0000, 0xb3f40000)
       the space 4096K,  26% used [0x966a0000, 0x967b01b0, 0x967b0200, 0x96aa0000)
    compacting perm gen  total 12288K, used 9169K [0xb3f40000, 0xb4b40000, 0xb7f40000)
       the space 12288K,  74% used [0xb3f40000, 0xb4834740, 0xb4834800, 0xb4b40000)
    No shared spaces configured.CLASS1:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.RepaintManager;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TestClass2 extends JFrame implements ActionListener {
            /** Action Command for <code>searchbtn</code> */
            public static final String SEARCH_BTN_ACTION = "search_btn_action";
             * Constructor.
            public TestClass2() {
                    setSize(650, 350);
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    setLocation(screenSize.width / 2 - getSize().width / 2,
                                    screenSize.height / 2 - getSize().height / 2);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    exit();
                    JPanel panel = new JPanel();
                    add(panel);
                    setVisible(true);
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals(SEARCH_BTN_ACTION)) {
                            JOptionPane.showMessageDialog(this, "Button Pressed");
            public void showWait() {
                    try {
                            WaitDialog.showWaitDialog(this, "Testing...", new SwingWorkerInterface(){
                                    @Override
                                    public Object workToDo() throws Throwable {
                                            Thread.currentThread().sleep(3000);
                                            return null;
                    } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (ExecutionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
             * Exits the program.
            public void exit(){
                    System.exit(0);
             * Create the GUI and show it. For thread safety, this method should be
             * invoked from the event-dispatching thread.
             * @throws UnsupportedLookAndFeelException
             * @throws IllegalAccessException
             * @throws InstantiationException
             * @throws ClassNotFoundException
             * @throws NullInstanceVariableException
             * @throws SQLException
            private static void createAndShowGUI() {
                    // set look and feel
                    try{
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                            // Create instance of the ProductCatalog
                            TestClass2 root = new TestClass2();
                            for(int i = 0; i < 10; i++){
                                    root.showWait();
                    }catch(Exception e){
                            e.printStackTrace();
             * @param args
             *            this program does not use arguments
            public static void main(String[] args) {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    createAndShowGUI();
    }CLASS 2:
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class WaitDialog extends JDialog {
            private boolean disposed = false;
            private boolean displayed = false;
            private WorkerThread worker = null;
            WaitDialog(Frame parent, String text, SwingWorkerInterface in){
                    super(parent, true);
                    worker = new WorkerThread(in);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowOpened(WindowEvent e) {
                                    worker.execute();
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    disposeWaitDialog();
                    this.setResizable(false);
                    JLabel message = new JLabel();
                    message.setText(text);
                    JProgressBar pb = new JProgressBar();
                    pb.setIndeterminate(true);
                    // set size and location
                    setSize(200, 100);
                    setLocationRelativeTo(parent);
                    JPanel panel = new JPanel();
                    panel.add(message);
                    panel.add(pb);
                    add(panel);
            public void showWaitDialog(){
                    if(displayed == true){
                            return;
                    if(disposed == true){
                            disposed = false;
                            return;
                    disposed = false;
                    displayed = true;
                    setVisible(true);
            public void disposeWaitDialog(){
                    if(disposed == true){
                            return;
                    if(displayed == true){
                            displayed = false;
                            setVisible(false);
                            return;
                    disposed = true;
                    displayed = false;
            public static Object showWaitDialog(Component parent, String text, SwingWorkerInterface in) throws InterruptedException, ExecutionException {
                    WaitDialog waitDialog = null;
                    if (parent == null) {
                            waitDialog = new WaitDialog(JOptionPane.getRootFrame(), text, in);
                    } else {
                            waitDialog = new WaitDialog(JOptionPane.getFrameForComponent(parent), text, in);
                    while(!waitDialog.worker.isDone()){
                            System.out.println("about to show");
                            waitDialog.showWaitDialog();
                            System.out.println("done showing");
                    waitDialog.dispose();
                    return waitDialog.worker.get();
            class WorkerThread extends SwingWorker<Throwable, Void> {
                    private SwingWorkerInterface in = null;
                    WorkerThread(SwingWorkerInterface in){
                            this.in = in;
                    public Throwable doInBackground(){
                                    try {
                                            System.out.println("about to do work");
                                            in.workToDo();
                                            System.out.println("done work no exception");
                                    } catch (Throwable e) {
                                            System.out.println("done work with exception");
                                            return e;
                                    return null;
                    public void done(){
                                    System.out.println("about to dispose");
                                    disposeWaitDialog();
                                    System.out.println("disposed");
    }CLASS 3:
    public interface SwingWorkerInterface {
            public Object workToDo() throws Throwable;
    }

    There's nothing directly wrong with it, but it will
    prevent other threads acquiring the class lock - but
    that may be what you want.True. Although the typical case for code that looks like this would be to use wait--usually the various threads in question require the same lock, so you have to use wait in order for the waiting thread to give it up and allow the other thread to do its work. Hard to say for sure though what he's doing.
    Also, if loading is all that the other thread does, and you're waiting for that thread to die, use join. But then, if that's the case, and you're only waiting for a single other thread, then you might as well just put it all in one thread, as already indicated.

  • How to synchronize two Event Dispatcher threads?

    I have two applications running in the same jvm. The flow should go like--
    a) First application (A1) has a swing window containing componets like buttons, text boxes etc.
    b) On click of this button, Event Dispatcher thread (T1) , calls the other application (A2).
    c) The second application A2, creates a swing window using EventQueue.invokeLater method and in the mean time Thread T1 should wait for this new A2 window to get some results from the database.
    Is it possible to stop thead T1 in between without freezing the GUI components of application A2.
    Thanks

    I think what tjacobs01 is getting at, is that there is only one Event Dispatcher Thread per JVM. So your question does not make sense. If there really is two EDT threads, then you are dealing with inter-process communication (since there would be two JVM processes, one for each application).
    It sounds like there is only one JVM, one EDT and two instances of a java.awt.Window. You probably think of the window == an application. In that case, you can probably solve your problem by executing the DB access (the long-running task) in the doInBackground() method of a SwingWorker.
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • WHY more Event-Dispatching threads in Applet ?

    When an applet is running, I find there are more than one Event-Dispatching Thread (EDT). I observed this through the Java Plug-in debug option -- attaching jdb.
    Swing Applications requires, access to any GUI object strictly on an Event-Dispatching Thread. Taking Event-Dispatching Thread to be a single thread, lots of synchronization consideration have been overlooked. When executing as an application, there is only one EDT; however when executing an an Applet there is more than one EDTs, but belonging to different thread groups. (like main, applet etc).
    WHY is this ?
    From a GUI developer's perspective is it safe to assume EDT is single threaded and NO sychronization issues needs to be taken care, which otherwise will be required ?
    Please let me know if you would require any more information to answer this query.
    Thanks a lot, in advance, for your time and effort. :-)
    -Soms.

    MORE supporting information:
    The jdb Thread information: (Note that there are 2 EDTs - Main and applet thread groups). I need to know WHY 2 EDTs ?
    threadsGroup system:
    (java.lang.ref.Reference$ReferenceHandler)0x9c0 Reference Handler cond. waiting
    (java.lang.ref.Finalizer$FinalizerThread)0x9c1 Finalizer cond. waiting
    (java.lang.Thread)0x9c2 Signal Dispatcher running
    (java.lang.Thread)0x9c3 Thread-1 unknown
    (sun.plugin.cache.CleanupThread)0x9c4 Cache Cleanup Thread cond. waiting
    Group main:
    (java.lang.Thread)0x9c6 main running
    (java.util.logging.LogManager$Cleaner)0x9c7 Thread-0 unknown
    (java.lang.Thread)0x9c8 AWT-Shutdown cond. waiting
    (java.lang.Thread)0x9c9 AWT-Windows running
    (java.lang.Thread)0x9ca Java2D Disposer cond. waiting
    (java.awt.EventDispatchThread)0x9cb AWT-EventQueue-0 waiting in a monitor
    Group Plugin Thread Group:
    (java.lang.Thread)0x9ce Main Console Writer cond. waiting
    Group http://rndpc192/periview/-threadGroup :
    (java.lang.Thread)0x9cf thread applet-com.peri.rnd.monitor.alaska.AlaskaApplet.class cond. waiting
    (java.lang.Thread)0x9d0 TimerQueue cond. waiting
    (java.awt.EventDispatchThread)0x9d1 AWT-EventQueue-2 waiting in a monitor
    (java.lang.Thread)0x9d2 Thread-4 waiting in a monitor
    (java.lang.Thread)0x9d3 Thread-5 unknown
    (java.lang.Thread)0x9d4 Thread-8 unknown
    (java.util.TimerThread)0x9d5 Thread-9 cond. waiting
    (java.lang.Thread)0x9d6 Thread-10 running
    (java.lang.Thread)0x9d7 Thread-12 unknown
    (java.util.TimerThread)0x9d8 Thread-13 waiting in a monitor
    (java.lang.Thread)0x9d9 Thread-14 waiting in a monitor
    (java.lang.Thread)0x9da Thread-15 cond. waiting

  • Help!Can someone tell me the detail about Event Dispatch thread!

    I want to know the whole process about swing event,for example,the detail about
    event dispatch thread,the relation about event dispatch thread with event queue,and how the JVM painting the screen etc.
    Thanks!

    Read the tutorial titled "Creating a GUI Using JFC/Swing" found on this page":
    http://java.sun.com/docs/books/tutorial/
    Take a look at the table of contents, there is a section on threads which discusses the event thread and there are sections on painting. Actually take the time to read the whole tutorial.

  • Two Event Dispatch threads?

    I took a core dump of my swing app and it shows 2 threads in the following name (*AWT-EventQueue-0, AWT-EventQueue-1*). When does this happen? I know there could be only one Event dispatch thread. Please clarify! Tks
    name: AWT-EventQueue-1 id: 155 daemon: false alive: true priority: 6 state: WAITING thread group: java.lang.ThreadGroup[name=javawsSecurityThreadGroup,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), java.lang.Object.wait(Object.java:485), java.awt.EventQueue.getNextEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]
    name: AWT-EventQueue-0 id: 29 daemon: false alive: true priority: 6 state: TIMED_WAITING thread group: java.lang.ThreadGroup[name=main,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), com.lb.stomp.tiger.gui.Level2View.setClientMode(Level2View.java:87), com.lb.stomp.tiger.gui.Level2View.doClientModeRefresh(Level2View.java:302), com.lb.stomp.tiger.gui.Level2View.access$100(Level2View.java:44), com.lb.stomp.tiger.gui.Level2View$4.run(Level2View.java:291), java.awt.event.InvocationEvent.dispatch(Unknown Source), java.awt.EventQueue.dispatchEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]

    Please answer me direct if you have anything to add or please let someone else answer that knows about it.WARNING:
    You'll not like my reply...
    ok now I change my stance and saying my question is not related to what I am trying to investigate on my app. If this is irony towards tjacobs' reply, be prepared for a culture schock around here.
    Lot of (most?) problems submitted here end up being solved very differently than what the questions started as. Often a poster will ask a narrow question, be asked about the context and reason for asking it, disclose what his real problem is, be warned that the problem may be orthogonal to his question, and be advised to attack and solve it in a very different way.
    Posters of questions solved this way are generally grateful, although sometimes they may be deterred by what they feel is a dismissing or blurring of their original question.
    The "which secret are you hiding" is a recurrent whinning too, and is, how to say it nicely,... utterly unprofesional and childish (at best).
    Keep in mind that all people here are volunteers, and bear on their time to help other people out. It is a nonsense to groan that someone offering you a hand is secretly plotting against you gaining knowledge. If he really was, he wouldn't answer you in the first place.
    Just a curious question as to why would there be 2 AWT-EventQueue threads. This can happen with applets is what I read. This swing app was simply lauched from a command prompt.Now I like it better.
    I can't answer your question, and my curiosity is piqued as well.
    Although it's a reasonable assumption that there is only one event queue per application context, and one thread serving it, the docs go a long way saying that it's implementation-dependant. I found this paragraph in the docs (+<JDK_HOME>/docs/api/java/awt/doc-files/AWTThreadIssues.html+):
    The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting. The only restrictions imposed on the behavior of this machinery are as follows:
    * EventQueue.isDispatchThread returns true if and only if the calling thread is the event dispatch thread started by the machinery;
    * AWTEvents which were actually enqueued to a particular EventQueue (note that events being posted to the EventQueue can be coalesced) are dispatched:
    o Sequentially.
    That is, it is not permitted that several events from this queue are dispatched simultaneously.
    o In the same order as they are enqueued.
    That is, if AWTEvent A is enqueued to the EventQueue before AWTEvent B then event B will not be dispatched before event A.
    * There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable).
    So, since we agree that it's implementation-dependant, could you add here your system's specs (OS, JRE version)?

  • CODE TRICK: event dispatch thread and tables

    This is a handy little trick for all you MVC users out there...
    I was working on a table class and I had this little issue that came up about not calling the AbstractTableModel's update (fireXxx()) methods from outside the event dispatch thread.
    As I'm one to create my own table models anyway, to match my data source, I found this little trick, with a little help from java.awt.EventQueue, works nicely to let the method be called from any place without having to worry about what thread it's in. Seems to work well...
         * Overridden to make safe when calling from the event dispatch thread
         * or another thread.
         * @see javax.swing.table.AbstractTableModel#fireTableRowsUpdated(int, int)
        public void fireTableRowsUpdated(final int firstRow, final int lastRow)
            if(EventQueue.isDispatchThread())
                super.fireTableRowsUpdated(firstRow, lastRow);
            else
                try
                    // could use invokeLater, depending on your needs
                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run()
                            MyTableModel.super.fireTableRowsUpdated(firstRow, lastRow);
                catch (Exception e)
                    e.printStackTrace();
        }

    http://java.sun.com/products/jfc/tsc/articles/timer/index.html

  • Executing Code outside of the Event Dispatcher Thread

    Hello,
    I have just come to learn that any actionPerformed() method that is called after an event occurs actually runs in the Event Dispatcher. So, for example, if you click on a button, any code that is run as a result is run in the event dispatcher.
    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread? Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    My questions are a result of this: How does one normally go about updating a GUI during a long process? I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?

    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread?
    Correct. So if your response to an action is, for example, creating a new bit of UI using data which is already in memory, you can just do it.
    Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    You will need to create a new thread: method calls are just control flow within the same thread.
    You should use an object which implements Runnable and then use "new Thread(foo).start()"
    My questions are a result of this: How does one normally go about updating a GUI during a long process?
    You have to hop back onto the EDT whenever an update is required. I'd suggest writing yourself a little reusable class or two to help you with this - such as a listener mechanism with an implementation which handles the thread hopping.
    I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?
    Yes.
    Should I use inner classes? I would prefer to keep them as separate classes within the same package.
    Depends on all sorts of things - sometimes anonymous or declared inner objects are the way forward, sometimes public class objects, sometimes generic helper objects and sometimes utility classes. There are all sorts of different scenarios. As I say, though, it's worth writing some utility/helper classes to reuse. Personally I don't find SwingWorker is ideal so I have my own. Note that an abstract Action implementation is a very useful one, since this is precisely where you need to be doing most of the thread hopping.

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Threads from threads

    hi,
    just wondering if it's ok to start a thread from within another thread?
    e.g. mythread extends runnable
    run{
    mySubThread sub = mySubThread();
    sub.start();
    }

    Everything in java is running in a thread. Therefore the answer to your question is YES.
    matfud

  • Pass messages between main thread and FX application thread

    I'm launching an FX Application thread from a Main thread using Application.launch [outlined here: {thread:id=2530636}]
    I'm trying to have the Aplication thread return information to the Main thread, but Application.launch returns void. Is there an easy way to communicate between the Main thread and the Application thread?
    So far I have googled and found:
    - MOM (Message Orientated Middleware)
    - Sockets
    Any thoughts/ideas/examples are appreciated - especially examples ;) - right now I am looking at using Sockets to show/hide the application and for passing data.
    What is the preferred method? Are there others which I have not found (gasp) via Google?
    Dave.
    Edited by: cr0ck3t on 30-Apr-2013 21:04
    Edited by: cr0ck3t on 30-Apr-2013 21:05

    Is there an easy way to get a reference to these objects from both the Main thread and the FX Application thread - called via Application.launch() from the Main thread? Or do I have to use Sockets or MOM?Not much to do with concurrent programming is what I would call easy. It seems easy - but it's not.
    You can kind of do what you are describing using Java concurrency constructs without using sockets or some Message Oriented Middleware (MOM) package.
    With the Java concurrency stuff you are really implementing your own form or lightweight MOM.
    If you have quite a complex application with lots of messages going back and forth then some kind of MOM package such as camel or ActiveMQ (http://camel.apache.org) is useful.
    You can find a sample of various thread interactions with JavaFX here:
    https://gist.github.com/jewelsea/5500981 "Simulation of dragons eating dwarves using multiple threads"
    Linked code is just demo-ware to try out different concurrency facilities and not necessarily a recommended strategy.
    If your curious, you could take a look at it and try to work out what it is, what it does and how it does it.
    The main pattern followed is that from a blocking queue:
    http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
    Note that once you call launch from the main thread, no subsequent statements in the main method will be run until the JavaFX application shuts down. So you can't really launch from the main thread and communicate with a JavaFX app from the main thread. Instead you need to spawn another thread (or set of threads) for communication with the JavaFX app.
    But really, in most cases, the best solution with concurrency is not to deal with it at all (or at least as little as possible). Write everything in JavaFX, use the JavaFX animation framework for timing related stuff and use the JavaFX concurrency utilities for times when you really need multiple thread interaction.
    http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
    To get further help, you might be better off describing exactly (i.e. really specific) what you are trying to do in a new question, perhaps with a sample solution in an sscce http://sscce.org

Maybe you are looking for

  • Photos not showing up in 'blog' list of entries?

    I've customized my blog entry pages, so the positioning of the photo has been altered ... but I'm still using the 'mask' (that was the placeholder for the still in the original template). But the picture is not showing up automatically in the Entries

  • Window Focus Lost After Saving Page - Any Way To Get It Back With Keyboard?

    I've recently begun using Safari for Windows after having used Opera for years, and have run into a problem with window focus that I didn't have with Opera. Specifically, if you save a web page in Safari, you then find that the following functions ar

  • Java connecting to the Internet

    Hello, i'm a 14 years old boy and I'm making a sort of Stratego in Java. But, I have a little problem, you can't play Stratego on one computer because you'll see your opponents pieces then. So, I would like to connect different computers with eachoth

  • Site to Site VPN issues between PIX506 and ASA5505

    Hello all, I have a PIX506 running 635, and an ASA5505 running 722. The PIX is at corporate and is setup for remote vpn access. The remote user VPN is working. I have also attempted to do a site to site vpn to the ASA, but its not working correctly.

  • Setting Region Attributes

    Trying to set some region attributes to control width and height of my region. Unfortunately the settings do not seem to work. I have entered width=700px, width:700px, "width=700px" and "width=700px", all with no luck. If I edit the region template d