How to run programs in Java forever? System. in. Is read () the only way?
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()" mean that it will block until there is input? Does this also work when launching Java applications using UNIX RC scripts – not manually from the command line?
I want to write a Java application to listen for HTTP connections The application will start automatically when the system boots (using UNIX RC script) This means that the application will continue to run - theoretically forever, until it stops purposefully What is the best way to implement it in the Java main () method?
Solution
Keeping the main method in Java does not automatically end the program
If the non daemon thread is no longer running, there is a JVM By default, the only non daemon thread is the main thread, which ends when you leave the main method, so stop the JVM
So either don't end the main thread (don't let the main method return), or create a new non daemon thread that never returns (at least before you want the JVM to end)
Since this rule is actually very reasonable, there is usually a perfect candidate to use such a thread For an HTTP server, for example, it can be a thread that actually accepts connections and hands them over to other threads for further processing As long as the code is running, the JVM will continue to run, even if the main method has already finished running