Reputation: 426
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
Upvotes: 4
Views: 105
Reputation: 533492
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.
Upvotes: 5
Reputation: 126664
I think there is a problem with the .isVisible() method and a general fail usage of while loop.
if I add some random sentence to the while loop, for example, System.out.flush();, it works
There is a question with a similiar problem "Why does while(true) loop just run once - Java" on the while loop
it runs with random method like System.out.println()
I think you should call something when the actual window in the other thread closes in this thread, so you don't have to wait.
Upvotes: 3