5

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?

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
MooseMan55
  • 524
  • 2
  • 6
  • 21

6 Answers6

2

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
mgtemp
  • 248
  • 3
  • 11
  • Would be able to previde sopme example code by any chance? That would be much appreciated! :) Thanks! – MooseMan55 Jul 01 '15 at 23:54
  • It's been a while since I wrote in java but here is some pseudo-code – mgtemp Jul 01 '15 at 23:57
  • That's ok, your age example actaully really helps a lot. So bassically the while loop is just waiting until the guesser hits the right age, but it technically could never happen, thus an infinite loop? right? – MooseMan55 Jul 02 '15 at 00:02
  • infinite means it will NEVER happen. this is a finite loop because even though it may take 10000000 attempts the user COULD eventually guess correctly. – mgtemp Jul 02 '15 at 00:03
  • Got it! So a TRUE infinite loop can never be useful becuse you always want to end it at some point? – MooseMan55 Jul 02 '15 at 00:06
  • Yup. As long as the loop has SOME possible way to end it is ok. – mgtemp Jul 02 '15 at 00:07
  • @mgtemp: That's not true in all cases. For example, you never, ever want the software running your wristwatch to end if possible. Because that would mean that your wristwatch would only work up to a certain date and time. You want your watch to run forever until the end of time (in theory batteries can be made solar or kinetic rechargable, but battery running out is not a condition you'd program for for wristwatch software (maybe you would for smartwatches)). Another example is LED blinking lights controller. You'd never program a stop condition. The off button simply stops supplying power – slebetman Jul 04 '15 at 01:24
0

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.

encrest
  • 1,757
  • 1
  • 17
  • 18
0

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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
0

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.

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
0

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);}  
    }  

}    
Prateek Kapoor
  • 947
  • 9
  • 18
0

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);
    }
}
JavaHopper
  • 5,567
  • 1
  • 19
  • 27