Unresponsive threading involving Swing and AWT-EventQueue

后端 未结 8 758
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 09:00

I have an application that is unresponsive and seems to be in a deadlock or something like a deadlock. See the two threads below. Notice that the My-Thread@101c

相关标签:
8条回答
  • 2020-12-05 09:25

    It is hard to tell with the little information you give us. Then the code is full of bad coding practice that basically every second line could cause some issues. So all I can do is some sophisticated guesses:

    The line 134 does not contain anything that could cause a lock, so the information in the stacktrace has to be off. I assume that commit is true, as otherwise the code would hang on the executor creation, which is sufficiently complex for the JVM to not optimize that out of the stacktrace. Therefore the line where it hangs has to be the clock.latch() call. I don't know what it does, but given the try/finally structure it has to be something important, maybe related to threading.

    Then the "why does it hang". As you already stated two threads try to access the Swing thread for some work, but at least one never returns, which obviously results in a deadlock of all Swing components. To block the Swing thread someone has to at least call it, but no single line in the code presented does that, so again: sophisticated guessing.

    The first synchronized statement cannot be the reason, as it has already been passed, the second is not in the stacktrace but considering that this one might be faulty, it could probably be just in the progress of being called thanks to JVM code re-ordering for optimization.

    That leaves two candidates for this issue: the one is the clock.latch(), which can cause an issue, but only if it internally does any form of synchronization, for example being declared as synchronized void latch(), although I cannot tell how this would block as there is too little information. But based on the code presented, I assume that the rest of the program is in equal bad shape, so that isn't this far off. The second possibility is the synchronized(pendingEntries), but again: there is no evidence in the data presented that could cause this, but given the example anything goes.

    0 讨论(0)
  • 2020-12-05 09:27

    Looking for an answer drawing from credible and/or official sources.

    Event Dispatch Thread and EventQueue

    Swing event handling code runs on a special thread known as the Event Dispatch Thread(EDT). Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not thread safe. All GUI related task, any update should be made to GUI while painting process must happen on the EDT, which involves wrapping the request in an event and processing it onto the EventQueue. Then the event are dispatched from the same queue in the one by one in order they en-queued, FIRST IN FIRST OUT. That is, if Event A is enqueued to the EventQueue before Event B then event B will not be dispatched before event A.

    SwingUtilities class has two useful function to help with GUI rendering task:

    • invokeLater(Runnable): Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread(EDT). This will happen after all pending AWT events have been processed, as is described above.
    • invokeAndWait(Runnable): It has the same function as the invokeLater but it differs from invokeLater for the fact that:
      1. invokeAndWait waits for the task given by it to the EDT, to finish before returning.
      2. it blocks(awaits) the current(i.e., it's invoking thread from continuing it's execution by sending to WAIT state by means of synchronizing a lock.
      3. It will release the lock once the event request posted by this function gets dispatched in the EDT and the invoker thread of this function can continue.

    The source code has the evidence:

      public static void invokeAndWait(Runnable runnable)
        throws InterruptedException, InvocationTargetException {
    
         if (EventQueue.isDispatchThread()) 
              throw new Error("Cannot call invokeAndWait from the event dispatcher thread");
    
         class AWTInvocationLock {}
         Object lock = new AWTInvocationLock();
    
         InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), 
                                                     runnable, lock,
                                                     true);
    
         synchronized (lock) {  //<<---- locking
               Toolkit.getEventQueue().postEvent(event);
               while (!event.isDispatched()) { //<---- checking if the event is dispatched
                      lock.wait(); //<---- if not tell the current invoking thread to wait 
                  }
                }
    
          Throwable eventThrowable = event.getThrowable();
          if (eventThrowable != null) {
              throw new InvocationTargetException(eventThrowable);
          }
      }
    

    This explains the issue:

    My-Thread has just called java.awt.EventQueue.invokeAndWait(). So AWT-EventQueue-0 blocks My-Thread (I believe).

    To explain a scenario of deadlock which you are likely having, lets look into an example:

    class ExampleClass 
    {
    
        public synchronized void renderInEDT(final Thread t)
        {
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
    
                        @Override
                        public void run() {
                            System.out.println("Executinf invokeWait's Runnable ");
                            System.out.println("invokeWait invoking Thread's state: "+t.getState());
    
                            doOtherJob();
                        }
                    });
                } catch (InterruptedException ex) {
                    Logger.getLogger(SwingUtilitiesTest.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(SwingUtilitiesTest.class.getName()).log(Level.SEVERE, null, ex);
                }
    
        }
    
        public synchronized void renderInEDT2(final Thread t)
        {
                    SwingUtilities.invokeLater(new Runnable() {
    
                        @Override
                        public void run() {
                            System.out.println("Executing invokeLater's Runnable ");
                            System.out.println("invokeLater's invoking Thread's state: "+t.getState());
                            doOtherJob();
                        }
                    });
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(ExampleClass.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
    
        public synchronized void doOtherJob()
        {
            System.out.println("Executing a job inside EDT");
        }
    }
    

    As you can see, i have declared three synchronized function:

    1. renderInEDT(final Thread t): to execute a Runnable task in the EDT bySwingUtilities.invokeAndWait
    2. renderInEDT2(final Thread t): to execute a Runnable task in the EDT by SwingUtilities.invokeLater
    3. doOtherJob() : This function is invoked by each of the above two function's Runnable'S run() method.

    The reference of the invoking thread is passed to check the state for each of the invocation of SwingUtilities function. Now, if we invoke renderInEDT() on an instance exmpleClass of ExampleClass: Here Thread t is declared in the class context:

        t =  new Thread("TestThread"){
                     @Override
                     public void run() {
                        exmpleClass.renderInEDT(t);
                     }
    
        };
        t.start();
    

    The output will be:

    Executing invokeWait's Runnable 
    invokeWait invoking Thread's state: WAITING
    

    The doOtherJob() method never gets executed in the EDT posted by SwingUtilities.invokeAndWait because a deadlock situation appears. As the renderInEDT() is synchronized and being executed inside a thread namely t, the EDT will need to wait to execute doOtherJob() until first invoking thread is done executing the renderInEDT(final Thread t) method, as is described in the official tutorial source of synchronized method:

    it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

    Hence, EDT is waiting for the t thread to finish(and suspend) execution, but thread t is actually blocked and sent to waiting state by the SwingUtilities.invokeAndWait method as described above, hence it is not being able to finish it's execution: Bth of the EDT and the t thread is waiting for each other to be done with their execution.

    Let us see the above example with case: if we post event task using SwingUtilities.invokeLater as it will be evident if we execute the renderInEDT2() function on the exampleClass instance from a thread:

      t =  new Thread("TestThread"){
                     @Override
                     public void run() {
                        exmpleClass.renderInEDT2(t);
                     }   
        };
      t.start();
    

    This time you will see that, the function invocation continues normally producing following output:

    Executing invokeLater's Runnable 
    invokeLater's invoking Thread's state: TIMED_WAITING
    Executing a job inside EDT
    

    This time doOtherJob() gets executed by the EDT as soon as the first calling thread of renderInEDT2() is done executing it: to emphasize i have put the thread to sleep (3s) to inspect the execution timing and hence it shows the state TIMED_WAITING.

    This is what explains your second issue: As the exception is telling and also mentioned by you in one of your comment:

    enderOnEDT is synchronized on something way up in the call stack, the com.acme.persistence.TransactionalSystemImpl.executeImpl method which is synchronized. And renderOnEDT is waiting to enter that same method. So, that is the source of the deadlock it looks like. Now I have to figure out how to fix it.

    However,

    • SwingUtilities.invokeAndWait(Runnable) especially used while we want to block or awaits a thread and ask user confirmation if we should continue using JOptionPane/JDialogue/JFileChooser etc.
    • Otherwise, to post a GUI rendering task in the EventQueue, use SwingUtilities.invokeLater(Runnable).
    • Although, i have await the EDT using Thread.sleep(time) for demonstration purposes, Please don't do anything such, which might block the EDT for a mentionable amount of time even if it is few, otherwise your Swing will get frozen and will force you to kill it.
    • We should not perform any kind of computational work or read/write operation or any other thing that is not related to GUI rendering task inside EDT aka, inside the Runnable of the invokeAndWait and invokeLater function.

    At this point you yourself should be able to figure out and solve your problem because you are not providing enough details to us of your code. I think while posting your GUI rendering task to Event Queue using a synchronized function like enderOnEDT as you have said in your comment, then I don't see any reason for calling another synchronized function from it's Runnable. Rather put your rendering function in this Runnable directly. That is my sole purpose of explaining the Event Queue and EDT mechanism.

    Reference:

    1. The Event Dispatch Thread
    2. Class EventQueue
    3. Initial Threads
    4. SwingUtilities.invokeAndWait(Runnable doRun) documentation
    0 讨论(0)
提交回复
热议问题