Java Reference
In-Depth Information
The java.util.concurrent.atomic package contains atomic variable classes for
effecting atomic state transitions on numbers and object references. By replacing the long
counter with an AtomicLong , we ensure that all actions that access the counter state are
atomic. [5] Because the state of the servlet is the state of the counter and the counter is thread-
safe, our servlet is once again thread-safe.
We were able to add a counter to our factoring servlet and maintain thread safety by using an
existing thread-safe class to manage the counter state, AtomicLong . When a single element
of state is added to a stateless class, the resulting class will be thread-safe if the state is en-
tirely managed by a thread-safe object. But, as we'll see in the next section, going from one
state variable to more than one is not necessarily as simple as going from zero to one.
Where practical, use existing thread-safe objects, like AtomicLong , to manage your class's
state. It is simpler to reason about the possible states and state transitions for existing thread-
safe objects than it is for arbitrary state variables, and this makes it easier to maintain and
verify thread safety.
2.3. Locking
We were able to add one state variable to our servlet while maintaining thread safety by using
a thread-safe object to manage the entire state of the servlet. But if we want to add more state
to our servlet, can we just add more thread-safe state variables?
Search WWH ::




Custom Search