How to run a program forever in Java? Is System.in.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 input is entered? Will this also work when starting a Java application using a UNIX rc script - doesn't it start manually from the command line?

I would like to write a Java application to listen for HTTP connections. The application will start automatically when the system boots (using UNIX rc scripts). This means that the application will run continuously - theoretically forever, until it is intentionally stopped. What is the best way to implement this in the main () method of Java?

+6
source share
6 answers

Exiting the main method in Java does not exit the program automatically.

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, so stop the JVM.

Thus, either do not end the main thread (not allowing the main return method), or create a new non-daemon thread that never returns (at least until you want the JVM to end).

Since this rule is actually quite reasonable, there is usually an ideal candidate for such a stream. For an HTTP server, for example, it may be a stream that actually accepts connections and passes them to other streams for further processing. As long as this code works, the JVM will continue to work, even if the main method has been completed a long time ago.

+15
source

It looks like weird black magic, but the trick is very elegant.

 Thread.currentThread().join(); 

As a result, the current main thread, for example, waits for join() for the main thread, which by itself, to complete. In a deadlock.

A blocked thread does not have to be a daemon thread.

+26
source
Answer to

@Joachim is correct.

But if (for some reason) you still want to block the main method indefinitely (without polling), you can do this:

 public static void main(String[] args) { // Set up ... try { Object lock = new Object(); synchronized (lock) { while (true) { lock.wait(); } } } catch (InterruptedException ex) { } // Do something after we were interrupted ... } 

Since the lock object is available only for this method, nothing can notify it, so the call to wait() will not be returned. However, some other threads can unlock the main ... thread by interrupting it.

+5
source

while (true) { ... } should last quite a while. Of course, you will have to figure out how to stop it in the end.

A common trick is to have some volatile boolean running = true , and then the main be while (running) { ... } and define some criteria by which the thread sets running = false .

+1
source

Back to the topics, this is exactly what I wanted. By the way, this amazing tutorial helped me a lot.

Main.java

 public class Main { public static void main(String args[]) { ChatServer server = null; /*if (args.length != 1) System.out.println("Usage: java ChatServer port"); else*/ server = new ChatServer(Integer.parseInt("8084")); } } 

and the ChatServer.java class extends Runnable

 public class ChatServer implements Runnable { private ChatServerThread clients[] = new ChatServerThread[50]; private ServerSocket server = null; private Thread thread = null; private int clientCount = 0; public ChatServer(int port) { try { System.out.println("Binding to port " + port + ", please wait ..."); server = new ServerSocket(port); System.out.println("Server started: " + server); start(); } catch(IOException ioe) { System.out.println("Can not bind to port " + port + ": " + ioe.getMessage()); } } public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } .... pleas continue with the tutorial 

So, in the main method Runnable starts and a new thread, as shown in the figure, public void start() { is created using runnable. This causes the JVM to continue the process until the project or debugger exits.

Btw, the same as Joachim Sauer, published in his answer.

+1
source

We can also do the same with ReentrantLock and call wait ():

 public class Test{ private static Lock mainThreadLock = new ReentrantLock(); public static void main(String[] args) throws InterruptedException { System.out.println("Stop me if you can"); synchronized (mainThreadLock) { mainThreadLock.wait(); } } 
-1
source

All Articles