In Java Concurrency In Practice, Section 2.1, it states:
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); // <-- isn't it possible for resp to be
// modified by mult. threads at once?
}
}
As indicated in the code above, what happens if multiple threads try to modify the same ServletResponse
variable.
From my understanding of memory allocation, the above class does not seem completely thread safe.
While the reference to the ServletRequest
and ServletResponse
are put on the local stack for the calling thread, the actual objects are stored on the heap --which is shared between all threads.
A stateless object saves no application data; it is idempotent. Each operation on the object is independent of any other operations.
To put it simply, a class instance is immutable when its internal state can't be modified after it has been constructed. A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe.
If an object created locally never escapes the method it was created in, it is thread-safe. In fact, you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
Here the stateless object is StatelessFactorization
class. It's stateless because it has no own state, namely it has no instance fields. Thus this object is thread-safe. The resp
is another object implementing the ServletResponse
interface and it may or may not be thread-safe. Here the thread-safety of resp
is not discussed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With