Java Reference
In-Depth Information
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless
of the scheduling or interleaving of the execution of those threads by the runtime environ-
ment, and with no additional synchronization or other coordination on the part of the calling
code.
Since any single-threaded program is also a valid multithreaded program, it cannot be thread-
safe if it is not even correct in a single-threaded environment. [2] If an object is correctly im-
plemented, no sequence of operations—calls to public methods and reads or writes of public
fields—should be able to violate any of its invariants or postconditions. No set of operations
performed sequentially or concurrently on instances of a thread-safe class can cause an in-
stance to be in an invalid state.
Thread-safe classes encapsulate any needed synchronization so that clients need not provide
their own.
2.1.1. Example: A Stateless Servlet
In Chapter 1 , we listed a number of frameworks that create threads and call your components
from those threads, leaving you with the responsibility of making your components thread-
safe. Very often, thread-safety requirements stem not from a decision to use threads directly
but from a decision to use a facility like the Servlets framework. We're going to develop a
simple example—a servlet-based factorization service—and slowly extend it to add features
while preserving its thread safety.
Listing 2.1 shows our simple factorization servlet. It unpacks the number to be factored from
the servlet request, factors it, and packages the results into the servlet response.
Listing 2.1. A Stateless Servlet.
Search WWH ::




Custom Search