日期:2014-05-17  浏览次数:20788 次

为什么javaweb里修改session不需要额外的线程同步?
一个session对应一个用户,但是用户的请求可能发了两个服务器,然后服务器可能两个线程同时处理这两个请求,同时想修改这个用户的session,那不是出问题了吗?但是我一直看书在修改session的时候都不额外给线程同步的,为什么?

------解决方案--------------------
观察到这个问题不简单


Servlets and JavaServer Pages (JSPs). The servlets framework is designed to handle all the infrastructure of deploying a web application and dispatching requests from remote HTTP clients. A request arriving at the server is dispatched, perhaps through a chain of filters, to the appropriate servlet or JSP. Each servlet represents a component of application logic, and in high-volume web sites, multiple clients may require the services of the same servlet at once. The servlets specification requires that a servlet be prepared to be called simultaneously from multiple threads. In other words, servlets need to be thread-safe.


Even if you could guarantee that a servlet was only called from one thread at a time, you would still have to pay attention to thread safety when building a web application. Servlets often access state information shared with other servlets, such as application-scoped objects (those stored in the ServletContext) or session-scoped objects (those stored in the per-client HttpSession). When a servlet accesses objects shared across servlets or requests, it must coordinate access to these objects properly, since multiple requests could be accessing them simultaneously from separate threads. Servlets and JSPs, as well as servlet filters and objects stored in scoped containers like ServletContext and HttpSession, simply have to be thread-safe.

因为它本身就是线程安全的