Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stopping an infinite loop

 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 System.in 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
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's about:


And create a separate Thread, which reads from System.in, and on a 'stop' read, allow it to call 'stopIt ();'?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use Thread/Runable to implement your program.
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for all your help guys.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic