Java Reference
In-Depth Information
fit if there are internal consistency requirements on the location set, in which case returning
a consistent snapshot is critical, or a drawback if callers require up-to-date information for
each vehicle and therefore need to refresh their snapshot more often.
4.3. Delegating Thread Safety
All but the most trivial objects are composite objects. The Java monitor pattern is useful when
building classes from scratch or composing classes out of objects that are not thread-safe. But
what if the components of our class are already thread-safe? Do we need to add an additional
layer of thread safety? The answer is . . . “it depends”. In some cases a composite made of
thread-safe components is thread-safe (
Listings 4.7
and
4.9
)
, and in others it is merely a good
start (
4.10
).
In
CountingFactorizer
on page 23, we added an
AtomicLong
to an otherwise
stateless object, and the resulting composite object was still thread-safe. Since the state of
CountingFactorizer
is
the state of the thread-safe
AtomicLong
, and since
Count-
ingFactorizer
imposes no additional validity constraints on the state of the counter,
it is easy to see that
CountingFactorizer
is thread-safe. We could say that
Count-
ingFactorizer
delegates
its
thread
safety
responsibilities
to
the
AtomicLong
: