Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

please help with server!!!  RSS feed

Stephanie Grasson
Ranch Hand
Posts: 347
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
I have a client applet which makes requests of my remote server. When a client makes a request to connect, the server starts a new thread for the new client using the code below:
UserThread clientThread = new UserThread(serverSocket.accept());
I have also added a button to allow me to stop my server, using the following code:
stopButton = new Button("Stop");
stopButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
listening = false;
history.append("listening = " + listening + "\n");
history.append("Stopping server\n");
When I press the Stop button, my TextArea "history" is updated to confirm that "listening" has been set to false. I would think that this should cause me to break out of the while loop. However, the code after the while loop never executes.
Could someone please tell me what I am doing wrong? I cannot find any sufficiently sophisticated examples. All the examples I see simply use:
to cause their server to listen forever.
Please advise!!!
Thank you in advance!
Jim Yingst
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably the JVM is looking at its local copy of the (instance?) variable listening, rather than accessing it from the instance on the heap each time through the loop. It accessed it once at the beginning of the method, and at the end of the method will update it again, but within the loop the JVM can take various shortcuts for optimization. This would have no effect for a single thread, but with multi-threading obviously it creates problems. You have two possible solutions:
1. Declare listening as volatile. This tells the compiler and JVM that its value can change at any time within the loop, and so it must be accessed from the heap each time it is referenced.
2. Access listening only through synchronized methods like getListening() and setListening().
Another thing to consider is that you may also be better off replacing the while loop with a wait()/notify() protocol, or responding to an event listener of some sort. I'm not really clear on how your while loop is intended to work - shouldn't you create just one new thread for a user? But in general, loops waiting for input are a needless drain on system resources if you can replace them ith something that only executes in response to a request. Worth considering anyway - maybe it's possible, maybe not.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!