• Post Reply Bookmark Topic Watch Topic
  • New Topic

Usage of while loop?  RSS feed

 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How could I go about terminating it more gracefully?

You could check if a certain file exist or not. If the file exists, the program would stop.
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Andre Brito
Ranch Hand
Posts: 95
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
I'm sorry my "dumbness", but the Observer pattern can't solve your problem (I mean, it's not a problem, but I guess that it could exclude the overhead of the system).

Am I wrong? If I am, I'm sorry :|
(sorry my english).

Hugs.
 
Don Solomon
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with you, Andre. Definitely an event/notification solution.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!