Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

servlets - In Java, How do I make sure my web application is thread safe?

How do I make sure my java servlets web application is thread safe? What do I need to do in regards to session variables, static variables of a class, or anything else that could be a thread-safety problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Fact: there's only 1 instance of a servlet in webapp's lifetime. It get created on webapp's startup and it get destroyed on webapp's shutdown. Also see this answer for a rough interpretation.

Thus, it's been shared among all requests (threads). If you assign request or session scoped data as instance (or even worse, as static) variable, then it is definitely not threadsafe, because it's then been shared among all requests (threads) from all users (sessions) applicationwide. You just need to assign them as method local variables to keep them threadsafe. So:

public class MyServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

That's basically all you need to take into account when developing servlets with threadsafety in mind.

Then there are session (HttpSession) attributes which can be shared among multiple requests from the same user, but in real world you actually don't need to worry about synchronizing session access. You normally put only user-specific data there, such as the logged-in user, user-specific preferences, the shopping basket, etcetera. You just need to ensure that you don't put pure request scoped data in the session scope. It would get reflected in multiple browser windows/tabs inside the same session.

Then there are application (ServletContext) attributes which are shared among all users applicationwide, but you normally put only constants and other static data there, like the webapp configuration, DAO factory, dropdownlist contents, etcetera. This all can by the way be done with a ServletContextListener, also see this answer for a basic example. You just need to ensure that you don't put pure request- or session scoped data in the application scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...