A way to keep a Java program running indefinitely?

My program runs basically and starts several threads that do the work of the program (reading sensors, updating the database, displaying information on the screen). I want the program to work indefinitely.

At the time my streams started mostly, I just:

public static void main(String []args)
{
    //threads start here
    while(true) {}
}

      

Obviously this works, but I'm wondering if it's wasting resources per loop.

Is there an efficient way to keep the program running. Is there a graceful way to exit? for example, start an event listener basically that listens for a keyboard or an event or whatever?

I also tried this if it's better:

while(true) {
    TimeUnit.HOURS.sleep(1);
}

      

EDIT: More information on streams:

I'm not sure what type of stream they are. I am implementing an interface called gnu.io.SerialPortEventListener that starts and processes threads, so it distracts from me. I need to take a look at the API, although I think it is poorly documented, or look at the source I think. They keep the JVM in the IDE (blueJ), but not when running the program at the command line. I am just using an interface method to add an event listener to the COM port that starts the threads.

+3


source to share


2 answers


If your threads are not daemon threads

, I don't understand why you have to have some time or, for that matter, any loops that your CPU will just eat. Your main thread will not be killed unless all non-daemon threads are terminated. Also, if you want to do the cleanup, you can register the JVM hookdown .



+5


source


I am doing something similar with RMI servers. Instead of an infinite while loop, you can use an infinite wait ().

private final Object forever = new Object();
synchronized (forever) {
  try { forever.wait() } catch (InterruptedException ignore) {}
}

      



Another problem is how to terminate this server? When I want to finish it, I start a new thread which issues System.exit (0); which is killing the JVM. Obviously, you need to program a way to access this code.

+1


source







All Articles