while loop not executed - java

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

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.

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.

Related

Why does a java program closes on termination but not a web browser

If I write a public static void main java program, unless I put a while (true) loop, the program will run and then exit, closing my applet window.
My question is when a web browser runs through rendering html content, after it has finished rendering, why doesn't it close itself? Where is the while (true) implicit in a web browser?
Java applications end because the call stack ends / is empty after your main() method has finished and they must jump back to the place they were called from (that's how method/functions calls are eventually implemented in assembly language). The main() method is special because it's the entry point of your whole Java program, the one that is called from the outside.
In a browser, your application code runs inside an event loop, not as part of the main browser process i.e. the one started through the main() method described above. The event loop, in an overly simplified version of a program, looks something like:
public static void main(String args[]) {
Queue queue = ...;
while(queue.waitForEvent()){
queue.processNextEvent();
}
}
So, in some sense. Yes, that implicit while(true) statement you're talking about is there, somewhere deep in each browser (and other event-loop based systems) implementation. The browser process won't close / terminate until something causes that event loop to stop running e.g. you closing the tab/window where your app is running.
A program started via main() can keep running, despite reaching the end of the main method. That can happen if you create new threads, which incidentally happens with GUI programs.
AWT (and swing by extension) have an event loop handling the event queue. Other toolkits handle it more or less similarly. They usually have a method/function that enters the loop. At least some also allow taking control of the toolkit's event loop, if the application needs more complete control. Then the loop can be explicit in the application code.
So, where exactly the loop is, depends on the browser implementation.

running background process at certain interval with different foreground process in java

I have 3 functions in a java program:
the first two are used for polling any SNMP device; all they do is get the inbound n outbound traffic.
the third function gets any value based on the input user enters.
The main function is menu driven. It asks users to enter choices as to what value they need and accordingly the value is returned using the third function.
While this goes on I want the first two functions to run every 5 seconds and it shouldn't mess with the menu driven program.
Any ideas on how to do that ?
p.s.: I tried a few exapmles but they reset the menu (do while loop) every time they are done with the first two functions.
Stab in the dark - would a Timer function calling a Task work?
For first two function you could use
while(true) {
thread1.start();
thread2.start();
Thread.sleep(5000);
}
For third thread you should make Deamon thread(by thread3.setDeamon(true)) which runs background. In the run method of every kind of thread(which don't forget to implements Runnable or extends Thread) you could make what work is thread doing. Good Luck!
You probably need to go the multithreading way because SNMP communication induce possibly long timeouts waiting for a reply, and you do not want the timeouts to freeze the interface (waiting on the UI thread would be bad).
To make it simple, one Thread could be used to communicate for the "two functions", polling alternatively function1() and function2() (can be extended later with a Thread Pool).
The main thread can be used for your main input (like normal java programs).
Snippet for threaded logic, where function1() and function2() are time-consuming (note: there is no sleep since cadencing would be done within the polling in your functions, if you need to reduce polling frequency, use wait(timeout) and notifyAll() -- necessary to quickly exit when the user clicks Exit menu) :
while ( ! isTerminated() )
{
function1();
if ( isTerminated() )
break;
function2();
}

Can't bring Java window to front when busy

I have written an image processing application with the GUI part written in Java and the number crunching part is written in C and is called via JNI.
My problem is that it takes 20 - 30 seconds for the application to process an image, and during this time the application disappears from the Task Switcher (the Alt-Tab thingy) and it is not possible to move the application's window to the front (this is my main concern). It is still possible to bring the application to front via the task bar.
Some more info:
The application isn't stuck or anything, I can see that it updates a progress bar as expected.
When the calculation is done, the application will show up the Task Switcher and can become the top window again. If I start a new calculation the application will disappear from the Task Switcher again.
The JNI call is made on a separate thread (from EDT), I have tried both the main thread and a created thread.
The EDT is not blocked. I have added printfs in WindowListener's and WindowFocusListener's methods and if the window lose focus the appropriate methods are called.
On Mac OS X the application works without problem.
This is on Java 1.6 on Windows 2003 Server.
First I thought that it was openMP that was doing something nasty with the threads, but turning it off didn't make any difference.
The JNI lib is compiled with MinGW 4.5.
It seems to me that Windows expects that an application answer/send some requests or else it will be thrown out of the Task Switcher. But I don't even know enough about Windows programming to even be able to google for an answer. Can someone give me some pointers?
I hate to say this as an answer, but are you sure that the number crunching is happening on a separate thread from the EDT? Because seriously, it shouldn't be behaving this way at all. There's a logical reason for it, I'm sure, and the most obvious is, you're blocking the EDT while you number crunch.
Maybe you think you're creating a new thread, but you're not?
Runnable r = new Runnable() {
public void run() {
ClassName.this.executeJNI();
}
};
new Thread(r).start();
Either that, or something in the number crunching is locking a resource that the EDT thread needs - but I don't even know what this could possibly look like.

Is my way of doing threads in Android correct?

I'm writing a live wallpaper, and I'm forking off two separate threads in my main wallpaper service. One updates, and the other draws. I was under the impression that once you call thread.start(), it took care of everything for you, but after some trial and error, it seems that if I want my update and draw threads to keep running, I have to manually keep calling their run() methods? In other words, instead of calling start() on both threads and forgetting, I have to manually set up a delayed handler event that calls thread.run() on both the update and draw threads every 16 milliseconds. Is this the correct way of having a long running thread?
Also, to kill threads, I'm just setting them to be daemons, then nulling them out. Is this method ok? Most examples I see use some sort of join() / interrupt() in a while loop...I don't understand that one...
No
No
For #1, I believe your threads are terminating. Once the run() method is left, the thread is considered terminated. If you want the thread to run "forever", you need to repeat your actions.
For #2, the thread will continue running even if you lose all references to it. I would suggest a signal or condition to the worker thread, followed by a join() in the main thread.
Like Yann said, if you keep having to restart your thread(s), it means you are probably not looping correctly.
Say your wallpaper just has a ball moving around the screen, this would be a sample run() method:
boolean isAnimating;
public void run() {
isAnimating = true;
while(isAnimating) {
moveBall();
isAnimating = isWallpaperVisible(); // or whatever conditions apply to not keep animating
}
}
This way your run method will keep running indefinitely.

How can I close my software in a safe way?

Up to now I used my application as a stand alone product. So, when user pressed "Stop" button I called System.exit(0); and it was fine.
Now my application will be called (in a programmatic way) from another program. So, I afraid that System.exit(0); will kill not only my process but also the external software which started my program.
So, what is the correct way to shutdown my application if a corresponding request from an external software is received? My application is an GUI application. So, I want to close the window but I also want to close all processes performed by my program.
ADDED:
To be more specific, I want to close all threads started by my program. My program does not start any OS process or any other program.
If the threads you've launched are still processing then calling System.exit(0) will cause them to be killed. In some cases, this can leave your application in an inconsistent state. Imagine that the thread was saving a file for example.
You should ensure that the your threads are all 'happy' to die before calling System.exit.
One technique you can use for this with long running threads is poisoning. To do this you send the threads a message that they should now die gracefully - i.e. a poson message. Once they have all died, it is safe to call System.exit(0) to terminate the Swing event handling thread.
There a loads of different ways of implementing poisoning, you could just set a global flag variable that the threads check to see if they've been poisoned, or you could use the Java 5 threading libraries. Take a look at this Javadoc for example and you'll find references to this technique:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
As long as your programm isn't sharing an application server with others, shuting down the VM by calling System.exit(0) terminates all threads.
From Javadoc
System.exit Terminates the currently running Java Virtual Machine)
EDIT:
If you want to do some clean up code before shutdown, http://java.sun.com/j2se/1.4.2/docs/guide/lang/hook-design.html
There is on "one-size-fits-all" answer to this that's a drop-in replacement for System.exit, unfortunately.
You will generally need to set some kind of flag that signals to all of your threads that it is time to exit, and ensure that they check this flag regularly. This will let them clean up gracefully without stopping abruptly, and it also ensures the effects are limited to your own components. In this case your application's main thread would also observe the flag, wait for all the "worker" type threads to finish and would then return all the way up the stack until your application's entry point was reached.
This question is not too dissimilar to the deprecated Thread.stop (etc) methods, especially with regards to replacing System.exit with something more respectful. In that light, the why is Thread.stop() deprecated page may be useful reading.
Throwing an exception (a custom one called something like ApplicationStopException) to unwind the stack of the main thread is not such a bad idea; this prevents you from having to handle the special logic all over your code and instead lets the "message" propagate to the higher levels, where they can take whatever action is needed to exit your program gracefully.
I recommend you to do flagging to stop the thread so that the thread will know when it has to stop. For GUI and window, you can call frame.dispose().
For System.exit(), I think it will not affect the caller, you may try to see what is the real effect but as other people already recommended, do not call it directly like that, just let the threads stop by itself

Categories