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.
- Create a
while loop
inside main() thread which waits for every 2 seconds and prints latest timestamp in console.- Code:
while (true) { .... }
- Code:
- Same way infinite
for loop
.- Code:
for ( ; ; ) { .... }
- Code:
- Use Timer Class.
- Complete Tutorial: Java Timer and TimerClass – Reminder
Want to generate OutOfMemoryError programmatically? Let me know what you think.
CrunchifyAlwaysRunningProgram.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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.
1 2 3 4 |
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:
1 2 3 4 5 6 7 8 9 10 |
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.