Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer holding value

 
Lisa D'Aniello
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everybody. It's been a while, but I'm trying to get back on track here...
I've read up on the StringBuffer, but I don't understand what's going on here. It might have something to do with the servlet lifecycle - I don't know...
Basically what is happening is that my string buffer is holding values that I don't want it to. I fill out a HTML form and use a servlet to display a string. It works fine the first time. So I close my browser and run the project again. This time the servlet displays the correct information - FOLLOWED by the information that was stored in the string buffer the first time.
Why is it retaining the previous value even though I've closed my browser and everything? Shouldn't the variables get re-instantiated each time the servlet is called? Portions of code are below. Any help would be greatly appreciated.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure your servlet is reinitialized? Just because the browser is closed doesn't mean the servlet is destroyed. For a test, put a simple System.out.println() in both the init() and destroy() methods.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your servlet container creates a single instance of your servlet and passes every request through that instance. Since you have your StringBuffer as a member variable, all requests that comes through are sharing that StringBuffer. If you have many users their threads could be running "at the same time" and mix up their contents to make things worse. Does that make sense?
The safest thing is to move the variable declaration inside doPost so it becomes a local variable. Then every request thread that enters doPost creates its own StringBuffer and discards it at method exit.
Easy rule: No member variables in Servlets! You can learn when to break it as an advanced topic one day.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic