Monday, May 24, 2010

In computer programming (java) when would you purposely use an infinite loop?

I was under the impression that an infinite loop was only an error, but i guess there are situations out there where an infinite loop can be applied. so ive heard.. what are instances in which one would use an infinite loop in their code?

In computer programming (java) when would you purposely use an infinite loop?
The two people above me took my answers. You might use infinite loops any time you're waiting for some action to occur. Such as (while x%26lt;0) {... do something until some action occurs that makes x%26gt;0 ...}. Such an action could be user input or a change in time.
Reply:If you were writing software that runs on a device, you would let it run for ever, or at least until it lost power.





I've used infinite loops, but they don't run infinitely. I break out of them on whatever condition applies to the situation.
Reply:shadow3Ds answer is most appropriate. When a server (Say an web server) listnes on a port you have to create an infinite loop. There's no other way u can listne on a port.





As for the wisdom "Writing programs with infinite loops isn't a good idea.........."





THATS the standard practice.
Reply:You can imagine that some software needs to be on all the time and monitoring things constantly, and it achieves this by using an psuedo infinite loop. One example is a server - it loops constantly so that it can handle each of the requests it gets and while it isn't getting any requests it just sits there waiting for them, prepared.
Reply:Writing programs with infinite loops isn't a good idea, but in a multi-threaded environment, you can write threads that act as services that have infinite loops.





For example, if you write an email client you may create a thread process that has an infinite loop which continually checks an email server every X seconds for new mail. The loop can be infinite because the thread that kicked off the process can also terminate it.


No comments:

Post a Comment