Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes StringBuffer holding value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer holding value" Watch "StringBuffer holding value" New topic

StringBuffer holding value

Lisa D'Aniello
Ranch Hand

Joined: Sep 25, 2003
Posts: 42
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

Joined: Oct 08, 2001
Posts: 2937
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

Joined: Jan 29, 2003
Posts: 8791
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.

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
I agree. Here's the link:
subject: StringBuffer holding value
It's not a secret anymore!