devxlogo

Servlet State

Servlet State

Question:
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?

Answer:
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

HttpRequest.getSession()

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);

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist