How to run a program forever in Java? Is System.in.read() the only way?
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.
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.
@Joachim's answer is correct.
But if (for some reason) you still want to block the main method indefinitely (without polling), then 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 only visible to this method, nothing can notify
it, so the wait()
call won't return. However, some other thread could still unblock the main
thread ... by interrupting it.