Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does invokeLater execute in the main thread?

Tags:

I just encountered this "bug", but I'm not sure if this is intended: Code:

public static Object someMethod(){     assert SwingUtilities.isEventDispatchThread();     return new Object(); }  public static void main(String[] args){     SwingUtilities.invokeLater(() -> someMethod().toString());//First Example     SwingUtilities.invokeLater(someMethod()::toString);//Second Example } 

In the first example someMethod is being executed on the swing Thread, but in the second example it is not, although it should be in my opinion.

Is this a bug or is this intended?

like image 393
RoiEX Avatar asked Jun 14 '17 11:06

RoiEX


People also ask

What does SwingUtilities InvokeLater do?

An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.

What is the difference between InvokeAndWait and InvokeLater?

Difference on InvokeLater vs InvokeAndWait in Swing 1) InvokeLater is used to perform a task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously. 2) InvokeLater is a non-blocking call while InvokeAndWait will block until the task is completed.

What is SwingUtilities InvokeLater new runnable ()?

SwingUtilities class has two useful function to help with GUI rendering task: 1) 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.


1 Answers

To me it seems like a misunderstanding on your side

The first line is like saying: "Ok, Swing, what I want you to invokeLater is someMethod().toString()". So Swing executes it

The second line is like saying: "Ok, Swing, what I want you to invokeLater is the method toString() of the object returned by the method someMethod()". A someMethod() method that I am executing right now

So the result is completely logical to me

Just keep in mind that before evaluating a function (in this case invokeLater) Java needs to evaluate all arguments. So in the first case Java evaluate a lambda function (no need to execute it) and in the second case it encounters a method invocation so it needs to execute it

like image 184
Alberto S. Avatar answered Oct 21 '22 11:10

Alberto S.