Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until Platform.runLater is executed using Latch

Tags:

java

javafx

What I am trying to achieve is to halt the thread and wait until doSomeProcess() is called before proceeding. But for some strange reason, the whole process got stuck at await and it never get into the Runnable.run.

Code snippet :

final CountDownLatch latch = new CountDownLatch(1); 
Platform.runLater(new Runnable() {
   @Override public void run() { 
     System.out.println("Doing some process");
     doSomeProcess();
     latch.countDown();
   }
});
System.out.println("Await");
latch.await();      
System.out.println("Done");

Console output :

Await
like image 418
xar Avatar asked Jun 07 '13 07:06

xar


1 Answers

The latch.countDown() statement will never be called since the JavaFX Thread is waiting for it to be called; when the JavaFX thread get released from the latch.wait() your runnable.run() method will be called.

I hope this code make the thing clearer

    final CountDownLatch latch = new CountDownLatch(1);

    // asynchronous thread doing the process
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Doing some process");
            doSomeProcess(); // I tested with a 5 seconds sleep
            latch.countDown();
        }
    }).start();

    // asynchronous thread waiting for the process to finish
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Await");
            try {
                latch.await();
            } catch (InterruptedException ex) {
                Logger.getLogger(Motores.class.getName()).log(Level.SEVERE, null, ex);
            }
            // queuing the done notification into the javafx thread
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Done");
                }
            });
        }
    }).start();

Console output:

    Doing some process
    Await
    Done
like image 147
Gustavo Ulises Arias Méndez Avatar answered Oct 12 '22 12:10

Gustavo Ulises Arias Méndez