Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateless objects are always thread-safe?

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?
    }
}

Question:

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.

like image 644
bcorso Avatar asked Sep 28 '15 03:09

bcorso


People also ask

What are stateless objects?

A stateless object saves no application data; it is idempotent. Each operation on the object is independent of any other operations.

Does immutable objects are thread-safe?

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.

Are local objects 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.

Which of the following are thread-safe?

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.


1 Answers

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.

like image 81
Tagir Valeev Avatar answered Oct 16 '22 20:10

Tagir Valeev