0

Context: I'm reading "Java Concurrency in Practice" by Brian Goetz and others (sorry others). On the beginning of my copy there is

@ThreadSafe
public class StatelessFactorizer implements Servlet {

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        encodeIntoResponse(resp, factors);
    }
}

(code sample from author is here however in book it looks as I added it above)

My quesiton is: while the 'service' method has some external references to some objects it potentially can do sth with it, for example change it's state. Thus if 2 threads call 'service' at the same time, that state will be modified from 2 places and the class is not thread safe. A I right?

The book I mentioned is about concurrency. Reader can know absolutely nothing about HTTP and/or Servlet. My instance of the book does not even state what is the 'Servlet' the 'StatelessFactorizer' implements. So as it can be anything, there can be no assumption like "Your methods are using different objects which shouldn't effect other requests". I mean you don't know what 'extractFromRequest(req)' and 'encodeIntoResponse(resp, factors)' do. As the chapter deliberates about stateless I assume the chapter is Servlet-agnostic.

Marian Paździoch
  • 8,813
  • 10
  • 58
  • 103
  • Regarding your edit, that's what the second duplicate is there for. `StatelessFactorizer` has no state, it's _stateless_. It's thread-safe because none of its state can be modified concurrently by multiple thread. If callers to `service`, for some reason, decide to pass the same set of parameters concurrently to the method, then **those callers** potentially have a race condition and are not thread safe (if they don't take reasonable precautions with synchronization or other locking mechanisms). – Sotirios Delimanolis Nov 06 '19 at 16:26
  • Now I get it but why won't you make an answer out of that? – Marian Paździoch Nov 06 '19 at 19:00

1 Answers1

1

Based on that req and resp are stateless

Stateless means that all requests are separate from each other so every request must contain enough information on their own to fulfill the request. That means that each transaction of message based model of HTTP is processed separately from each other.

Your methods are using different objects which shouldn't effect other requests

i is derived from a method which gets a stateless request so it's stateless

You can apply similar logic for factors

Therefore service method is thread safe

Ori Marko
  • 56,308
  • 23
  • 131
  • 233