Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Servlets
Expertise: Beginner
Sep 12, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Servlet State

I'm developing some applications with servlets. I've been declaring static variables to preserve state, but when two instances of the servlet run at the same time, the second instance overwrites the values of the first instance. What can I do?

Rather than preserve state with static variables, you should associate state with sessions. There may be multiple instances of a servlet running in a servlet engine and each instance may be serving requests from multiple clients.

Requests from different clients will cause different state changes. If you store states in static variables, other instances of the servlet may overwrite the values and so may requests from different clients.

To preserve state on a session basis, obtain the HttpSession associated with a client request using


You can associate values with the session by storing them in the session object with

setAttribute(String name, Object value)

By storing values in a session, you can preserve state on a per client basis.

Object myValue;
HttpSession session;

myValue = "some value"; session = request.getSession(); session.setAttribute("my.attribute", myValue);

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date