In Java Concurrency In Practice, Section 2.1 says:
Stateless objects are always thread safe.
And gives the following class as an example:
@ThreadSafe
public class StatelessFactorization implements Servlet {
public void service(ServletRequest req, ServletResponse resp){
BigInteger i = extractFromRequest(req);
BigInteger[] factors = factor(i);
encodeIntoResponse(resp, factors);
}
}
Question:
As indicated in the above code, what happens if multiple threads try to change the same variable ServletResponse.
From my understanding of memory allocation, the above class does not look completely thread safe.
As long as the link to ServletRequestand ServletResponseis pushed onto the local stack for the calling thread, the actual objects are stored on the heap, which is shared by all threads.
source
share