Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop not executed

I am developing a java project where an external microcontroller device is connected via serial port to the computer. I have a wait dialog in the java application, waiting for a command to execute on the microcontroller device. If the microcontroller doesn't respond within 10 seconds the application shuts down.

The problem is that some commands are too fast, and the microcontroller responds before the wait dialog becomes active. This causes the application to shutdown after ten seconds.

Here is the first idea I thought to wait for the dialog to be visible:

new Thread() {
    public void run() {
         while (!Main.mainFrame.waitDialog.isVisible()) {}
         Main.usbManager.start();
    }
}.start();

But the application is stuck in the while loop and the wait dialog is visible, but if I add some random sentence to the while loop, for example, System.out.flush();, it works and when the dialog is visible the program exits from the while loop.

How can I wait for the dialog to be visible?

Thanks

like image 836
Cako Avatar asked Feb 06 '23 16:02

Cako


1 Answers

Most GUI libraries are single threaded. This means that calls to it might not be thread safe, you are never guaranteed to see a change. In particular boolean values can be inlined, so you can be sure after a certain point you won't see a change in the value.

If you use something which slows down the loop, it won't optimise the code for a while (this is unreliable) or has a memory barrier like System.out.flush() does, then this optimisation won't occur.

A better way to poll might be to use Thread.yield() or Thread.sleep(40) to save yourself some CPU as well.

like image 85
Peter Lawrey Avatar answered Feb 19 '23 04:02

Peter Lawrey