Keep running Main() Thread Continuously

Java is pretty amazing. With list of thousands of APIs and utilities you could create any types of tutorials. Today I had a scenario in which I needed to have my program running forever.

Wanted to check upstart script in Ubuntu OS. I could definitely do that by running Tomcat process but why not we simply create a Java Program which runs forever.

Logic is very simple. There are multiple ways.

  1. Create a while loop inside main() thread which waits for every 2 seconds and prints latest timestamp in console.
    • Code: while (true) { .... }
  2. Same way infinite for loop.
    • Code: for ( ; ; ) { .... }
  3. Use Timer Class.

Want to generate OutOfMemoryError programmatically? Let me know what you think.

CrunchifyAlwaysRunningProgram.java

package crunchify.com.tutorial;

import java.util.Calendar;

/**
 * 
 * @author Crunchify.com 
 * Program: How to keep a program running until the user terminates it? 
 * Version: 1.0
 * 
 */

public class CrunchifyAlwaysRunningProgram {

        public static void main(String args[]) {

                CrunchifyAlwaysRunningProgram object = new CrunchifyAlwaysRunningProgram();
                object.waitMethod();

        }

        private synchronized void waitMethod() {

                while (true) {
                        System.out.println("always running program ==> " + Calendar.getInstance().getTime());
                        try {
                                this.wait(2000);
                        } catch (InterruptedException e) {

                                e.printStackTrace();
                        }
                }

        }
}

Please notice synchronized keyword in above program. If you remove that then at compile time there won’t be any exception but at run time you will see below exception.

Exception in thread "main" java.lang.IllegalMonitorStateException
        at java.lang.Object.wait(Native Method)
        at crunchify.com.tutorial.CrunchifyAlwaysRunningProgram.waitMethod(CrunchifyAlwaysRunningProgram.java:27)
        at crunchify.com.tutorial.CrunchifyAlwaysRunningProgram.main(CrunchifyAlwaysRunningProgram.java:18)

Now run your program and you will see below result.

Eclipse console result:

always running program ==> Fri Oct 06 20:46:29 CDT 2017
always running program ==> Fri Oct 06 20:46:31 CDT 2017
always running program ==> Fri Oct 06 20:46:33 CDT 2017
always running program ==> Fri Oct 06 20:46:35 CDT 2017
always running program ==> Fri Oct 06 20:46:37 CDT 2017
always running program ==> Fri Oct 06 20:46:39 CDT 2017
always running program ==> Fri Oct 06 20:46:41 CDT 2017
........
........
........

I hope you find this simple tutorial useful running your java program indefinitely.

The post How to Run a Program forever in Java? Keep running Main() Thread Continuously appeared first on Crunchify.