I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.
Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas?
You didn't say if this was a GUI/Swing or a command line application. I gather it is a command line program.
Another option besides the while(true) loop is to use the java.util.Timer class. A Timer can be set up to run one time, or repeatedly at a fixed interval. Your main thread then can monitor for input of an 'exit' command.
If your process runs in the background, you could have a 'keepRunning' flag. Implement a method to set it that can be called via RMI. Then write a simple 'shutdown' application that uses RMI to connect to the running background application to set the flag.