File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Stopping an infinite loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Stopping an infinite loop" Watch "Stopping an infinite loop" New topic

Stopping an infinite loop

Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
I have created a simple web server, that goes in a continuous loop to accept connections. This works fine. But now I need to implement a feature to be able to stop the server and the infinite loop, and I wasn't sure how to do this. So I basically want to be able to type in a command to stop the server. My problem is that when I use a BufferedReader from it just blocks if there is nothing to read, and in this instance I need the loop to continue. Here's the relevant code:

How can I can I stop the server if need be?

Thanks for any help.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

What's about:

And create a separate Thread, which reads from, and on a 'stop' read, allow it to call 'stopIt ();'?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
My Wiki executes command classes when you post forms. One of the forms triggers a shutdown command that sets a variable that stops the loop just as shown above. So I can just navigate to a page and hit a button to shut it down from anywhere. I also made a little standalone program that pretends to be a browser and posts the shutdown form. Oh, it is secured - you have to log in with a userid that has shutdown permission.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

Note that this field should almost certainly be declared 'volatile'.

'almost certainly' because you almost certainly will be changing the value from a thread other than the one executing the while loop.

Tony Morris
Java Q&A (FAQ, Trivia)
somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312
You should use Thread/Runable to implement your program.

Java Developer, Thailand
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
thanks for all your help guys.
I agree. Here's the link:
subject: Stopping an infinite loop