What are the practical applications for infinite loops in Java?
For example:
while(true){
//statements, but the loop is never set to false
}
When could you use this?
What are the practical applications for infinite loops in Java?
For example:
while(true){
//statements, but the loop is never set to false
}
When could you use this?
Infinite in the sense that until something changes you want it to keep running. So until the user hits "exit" keep running a program.
In your example you would need something in the code that eventually would break it.
if (this happens)
break
end
But then you might as well just put the boolean instead of counter < 1 in the while loop. So in your example it's bad practice.
program to guess age
initialize age
while (age != 20)
get guess from user
age = guess from user
end
If you had a job that checked to see if any work needed to be done, did the work, then repeated forever, you might write an infinite loop around that job. A slightly more efficient way to write your infinite loop would be:
while (true) {
//do job
}
Examples of such jobs might include rotating log files, copying/backing up user uploads etc.
I usually write threads that look something like this:
while(true) {
data = stream.read();
// process data
}
stream.read()
typically hangs until the data is served. This would just continually read, process that data, then wait for more.
In a lot of higher level applications, the while(true)
loops are hidden lower down (particularly in event based frameworks). For example, polling hardware. Somewhere in there there's a while(true)
or similar construct.
Simple hardware typically has just two functions: a setup function of some kind, followed by an infinite loop, actually called forever
in some places. The loop continues until the hardware is reset or turned off.
"Crash-only" server processes are often the same. By design, the only way to stop them is the software equivalent of yanking the plug.
Infinite loops can we useful, to perform certain task repeatedly until user want to exit.
while(true){
//perform some task
// value of flag changes in course of your program execution
if(flag){
break;
}
}
Also infinite loops can be used in case, where you want a thread to execute until the life time of application. You can mark these threads as daemon thread.
Historically, people used to use infinite loops while writing JMS receivers. But certainly now days,spring+JMS integration is preferred.
import javax.jms.*;
import javax.naming.InitialContext;
public class MyReceiver {
public static void main(String[] args) {
try{
//1) Create and start connection
InitialContext ctx=new InitialContext();
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
QueueConnection con=f.createQueueConnection();
con.start();
//2) create Queue session
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Queue object
Queue t=(Queue)ctx.lookup("myQueue");
//4)create QueueReceiver
QueueReceiver receiver=ses.createReceiver(t);
//5) create listener object
MyListener listener=new MyListener();
//6) register the listener object with receiver
receiver.setMessageListener(listener);
System.out.println("Receiver1 is ready, waiting for messages...");
System.out.println("press Ctrl+c to shutdown...");
while(true){
Thread.sleep(1000);
}
}catch(Exception e){System.out.println(e);}
}
}
I worked on the leading BPM product in the market.
It had infinite loop to run Agents (you can think of it as a background thread always running) to monitor certain things
For example: If Service Level Agreement (SLA) is breached, it would trigger an email alert or notify concerned parties
If you are a novice programmer, you can think of this use case : Menu driven program/application
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int choice = 0;
System.out.println("1. Add Book");
System.out.println("2. Delete Book");
System.out.println("3. View Books");
System.out.println("4. Exit");
while(true) {
//read input from console
String input = br.readLine();
choice = Integer.parseInt(input);
switch(choice) {
case 1: //code to add a book to library
break;
case 2: //code to delete a book from library
break;
case 3: //code to view all the books in library
break;
case 4://code to exit the application
System.exit(0);
}
}