I guess my question is, a JSP is compiled into a single servlet instance that serve multiple requests. How do I make it threadsafe?
4 Answers
Servlets are meant to be immutable. Either no state exists outside of method calls (the servlet is stateless), or any such state will never change (so the state that each thread sees is always the same).
It's extremely simple to write a threadsafe servlet: never use instance variables. Use method-local variables.

- 354,903
- 100
- 647
- 710
Try this: <%@ page isThreadSafe="true" %>

- 6,941
- 18
- 36
-
This is the default and it does not make the page ThreadSafe, it indicates to the container it can process concurrent requests safely... – Will Mar 22 '11 at 20:43
-
Thanak you for clarifying this for me. – Scicare Mar 24 '11 at 19:22
Just don't assign request/session specific data as global/static variables. So as long as you don't use scriptlet declarations <%! %>
which you assign with request/session specific data and you don't put request/session data in application scope (i.e. as attribute of ServletContext
), then you're safe.
See also:
JSPs are compiled into servlets. All JSP variables are method local (stack) variables hence they are thread safe.
If you directly add a thread-unsafe attribute to a servlet class, it will cease to be thread safe.

- 26,463
- 15
- 97
- 154