Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should SwingUtils.invokeAndWait() method be called outside an EDT thread?

Edit : I have referred this link and I'm able to understand the codeflow of InvokeLater. My question is, why is this logic implemented this way? Are there any specific reasons?


Following is my code:

  private void init() 
    {
    JFrame jfr = new JFrame();
    jfr.setSize(500, 500);
    jfr.setVisible(true);
    jfr.setTitle("Test");


    JButton jb = new JButton("Ok");
    jfr.add(jb);

    jb.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            try 
            {
                SwingUtilities.invokeAndWait(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
                        System.out.println("hello");
                    }
                });
            } 
            catch (Exception e1) 
            {
                e1.printStackTrace();
            } 
        }
    });

First Question (While using InvokeAndWait):

Why is it implemented in such a way that it throws an InvocationTargetException when called within EDT Thread?

Second Question (while using InvokeLater):

Why InvokeLater allows this ?

Well, this is my basic understanding on EDT threads:

InvokeAndWait:

  • Places job F into the EDT event queue and waits until the EDT has executed it.
  • This call blocks until all pending AWT events(A, B, C, D, E) have been processed and (then) execute F after which the control returns.
  • Returns if and only if the job submitted is completed.(Control returns after F is completed.)
  • Technically, a Synchronous blocking call.

InvokeLater:

  • Places the job F into the EDT Queue , but doesn't wait for its completion.(Basically , a publish and return call).
  • If we don't care about the job completion we can use InvokeLater.
  • Technically, a Asynchronous non-blocking call.
like image 510
Diya Avatar asked Jul 11 '16 11:07

Diya


1 Answers

EDT is the same as AWT. All UI events in AWT are scheduled on a single thread called EDT. Basically is the thread used to process UI related events in Swing.

InvokeAndWait: Basically you invoke a task on the same thread and then wait for that task to be completed. This would result in deadlock. Your method will never return cuz you are waiting for the task, the task will never run because your method will never be completed.

InvokeLate: It works because you are not waiting for that task to be completed. You invoke it in the exact same thread, but you are not waiting for it to complete, so this won't result in deadlock.

like image 167
Arpad Toth Avatar answered Oct 16 '22 15:10

Arpad Toth