StringBuffer and Synchronization

W

Wayne

I have a JSP that has a StringBuffer that is appended to 30 times and
at the end it is converted to a string with sb.toString(). The
problem I have with two almost instantanious executions of the JSP the
contents of the StringBuffer are mixed. I thought that StringBuffer
was thread safe. Any suggestions would help.

Thanks in advance
 
R

Robert Klemme

I have a JSP that has a StringBuffer that is appended to 30 times and
at the end it is converted to a string with sb.toString(). The
problem I have with two almost instantanious executions of the JSP the
contents of the StringBuffer are mixed. I thought that StringBuffer
was thread safe. Any suggestions would help.

Well, content is mixed - but in a thread safe manner. :)

Seriously, you probably have made the StringBuffer an instance variable
of the JSP. Consequently all invocations share the same instance (note
that a single JSP by default can be invoked multiple times
*concurrently*). You need to change it from an instance variable to a
local variable (i.e. created for every execution).

Regards

robert
 
L

Lew

Robert said:
Well, content is mixed - but in a thread safe manner. :)

Seriously, you probably have made the StringBuffer an instance variable
of the JSP. Consequently all invocations share the same instance (note
that a single JSP by default can be invoked multiple times
*concurrently*). You need to change it from an instance variable to a
local variable (i.e. created for every execution).

Even better, don't declare StringBuffers in JSPs at all. There is danger in
having to much Java scriptlet in a JSP; some would say none is the maximum.

(Marty Hall, author of / Core Servlets & JavaServer Pages/, is an infamous
excoriator of scriptlet in JSP.)

- Lew
 
D

Daniel Pitts

Even better, don't declare StringBuffers in JSPs at all. There is danger in
having to much Java scriptlet in a JSP; some would say none is the maximum.

(Marty Hall, author of / Core Servlets & JavaServer Pages/, is an infamous
excoriator of scriptlet in JSP.)

- Lew

Where I work (won't name names, but its a large media company), our
"legacy" JSPs have too much Java mixed in.

We are moving away from our legacy system, and our newer webapps don't
allow ANY java in JSPs. For the record, we use Spring MVC.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top