-1

Can anybody show me an example of what will happen if we did not use the invokeLater() method in Java?

class FibComputer implements Runnable{
    public void run(){
        final int result = fib(47);
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                jlbFib.setText(String.valueOf(result));
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

1

I suppose, jlbFib is a JLabel, and the FibComputer is intended to be run on some thread different from the event dispatching thread.

The package description for javax.swing says:

All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

The jlbFib.setText() call is such an access, so it's correctly wrapped in SwingUtilities.invokeLater(...).

If you don't do that, you risk running into any kind of thread-safety problems. Typically, in 90% of cases everything will look fine, sometimes the label won't get updated correctly, sometimes maybe your layout gets crumbled, or your GUI might even completely freeze.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
0

From the Oracle docs, In Swing programs, the initial threads don't have a lot to do. Their most essential job is to create a Runnable object that initializes the GUI and schedule that object for execution on the event dispatch thread. Once the GUI is created, the program is primarily driven by GUI events, each of which causes the execution of a short task on the event dispatch thread. Application code can schedule additional tasks on the event dispatch thread (if they complete quickly, so as not to interfere with event processing) or a worker thread (for long-running tasks).

An initial thread schedules the GUI creation task by invoking javax.swing.SwingUtilities.invokeLater or javax.swing.SwingUtilities.invokeAndWait . Both of these methods take a single argument: the Runnable that defines the new task. Their only difference is indicated by their names: invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning.

Coming to your point, I believe your application is swing application. If you didn't use the invokeLater method, then how you will create and initialize Runnable object, because by creating object for Runnable means your defining a new task, that is going to execute the run() method.

Arvind Katte
  • 995
  • 2
  • 10
  • 20