Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a program forever in Java? Is System.in.read() the only way?

Tags:

java

I took this code:

 28     public static void main(String[] args) throws IOException {
 29         HttpServer httpServer = startServer();
 30         System.out.println(String.format("Jersey app started with WADL available at "
 31                 + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
 32                 BASE_URI, BASE_URI));
 33         System.in.read();
 34         httpServer.stop();
 35     } 

Does line 33 "System.in.read()" means that it will block until there is input? Will this also work when starting the Java application using UNIX rc script - not manually started from a command line?

I'd like to write a Java application to listen for HTTP connections. The application will be started automatically when the system boots (using UNIX rc scripts). It means that the application will run continuously - theoretically forever, until purposefully stopped. What is the best way to implement this in the Java main() method?

like image 784
ikevin8me Avatar asked Aug 30 '12 14:08

ikevin8me


2 Answers

It looks like a weird black magic but following does the trick in very elegant way

Thread.currentThread().join();

As a result the current thread, main for instance, waits on join() for thread main, that is itself, to end. Deadlocked.

The blocked thread must not be a daemon thread of course.

like image 150
Stepan Vavra Avatar answered Sep 23 '22 02:09

Stepan Vavra


Leaving the main method in Java does not automatically end the program.

The JVM exists if no more non-daemon threads are running. By default the only non-daemon thread is the main thread and it ends when you leave the main method, therefore stopping the JVM.

So either don't end the main thread (by not letting the main method return) or create a new non-daemon thread that never returns (at least not until you want the JVM to end).

Since that rule is actually quite sensible there is usually a perfect candidate for such a thread. For a HTTP server, for example that could be the thread that actually accepts connections and hands them off to other threads for further processing. As long as that code is running, the JVM will continue running, even if the main method has long since finished running.

like image 31
Joachim Sauer Avatar answered Sep 26 '22 02:09

Joachim Sauer