Cako Cako - 1 year ago 112
Java Question

while loop not executed

I am developing a project where is involved a java software and an external microcontroller device connected via serial port to the computer. I have a wait dialog in the java application meanwhile a command is executing on the microcontroller device and if the microcontroller doesn't respond in 10 seconds the application shutwdowns.

The problem is that some commands are too fast that the java app hasn't shown the wait dialog when the response has been processed in another thread of the application and then shows the wait dialog, making 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()) {}

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,
, it works and when the dialog is visible the program exits from the while loop.

How can I do to wait for the dialog to be visible?


Answer Source

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.yeild() or Thread.sleep(40) to save yourself some CPU as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download