Why is (javax.servlet.)SingleThreadModel deprecated?
Why is javax.servlet.SingleThr开发者_开发知识库eadModel
deprecated?
The javadoc says why. SingleThreadModel
was designed to be an easy solution to low-load concurrency, but it didn't even manage that:
Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources.
If it can't achieve what it was designed for, it should not be used.
It's basically a poor way of handling concurrency. Take the state out of your servlet instead, so that the same servlet can be used by multiple threads concurrently. Keeping state in a "pool" of servlet instances, each of which can have state left over from the previous request etc is pretty horrible.
Yes SingleThreadModel interface is deprecated. Do not use it. In fact you don't need it, instead use local variables instead of object fields since "each thread gets its own copy of local variables in Java. By simply removing the object field and replacing it with a local variable, this particular threading problem is resolved." Reference
From Java Servlet Spec:
The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in a given servlet instance’s service method. It is important to note that this guarantee only applies to each servlet instance, since the container may choose to pool such objects. Objects that are accessible to more than one servlet instance at a time, such as instances of HttpSession, may be available at any particular time to multiple servlets, including those that implement SingleThreadModel.
It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. The SingleThreadModel Interface is deprecated in this version of the specification.
If a servlet implements SingleThreadModel
interface, servlet container can create one or multiple instance of the servlet depend on the request load. Each instance will use only their service()
method. It solves thread safety issues but not all of them. Such as static class variables, session attributes are still not thread safe.
Instead of using this interface developer encouraged to use synchronizing the block of the code accessing those resources.
精彩评论