Java Reference
In-Depth Information
StatelessFactorizer is, like most servlets, stateless: it has no fields and references no
fields from other classes. The transient state for a particular computation exists solely in local
variables that are stored on the thread's stack and are accessible only to the executing thread.
One thread accessing a StatelessFactorizer cannot influence the result of another
thread accessing the same StatelessFactorizer ; because the two threads do not share
state, it is as if they were accessing different instances. Since the actions of a thread accessing
a stateless object cannot affect the correctness of operations in other threads, stateless objects
are thread-safe.
Stateless objects are always thread-safe.
The fact that most servlets can be implemented with no state greatly reduces the burden of
making servlets thread-safe. It is only when servlets want to remember things from one re-
quest to another that the thread safety requirement becomes an issue.
2.2. Atomicity
What happens when we add one element of state to what was a stateless object? Suppose we
want to add a “hit counter” that measures the number of requests processed. The obvious ap-
proach is to add a long field to the servlet and increment it on each request, as shown in
UnsafeCountingFactorizer in Listing 2.2 .
Listing 2.2. Servlet that Counts Requests without the Necessary Synchronization. Don't do this.
Search WWH ::




Custom Search