Java Reference
In-Depth Information
We've used the terms “thread-safe class” and “thread-safe program” nearly interchangeably
thus far. Is a thread-safe program one that is constructed entirely of thread-safe classes? Not
necessarily—a program that consists entirely of thread-safe classes may not be thread-safe,
and a thread-safe program may contain classes that are not thread-safe. The issues surround-
ing the composition of thread-safe classes are also taken up in Chapter 4 . In any case, the
concept of a thread-safe class makes sense only if the class encapsulates its own state. Thread
safety may be a term that is applied to code , but it is about state , and it can only be applied
to the entire body of code that encapsulates its state, which may be an object or an entire pro-
gram.
2.1. What is Thread Safety?
Defining thread safety is surprisingly tricky. The more formal attempts are so complicated as
to offer little practical guidance or intuitive understanding, and the rest are informal descrip-
tions that can seem downright circular. A quick Google search turns up numerous “defini-
tions” like these:
. . . can be called from multiple program threads without unwanted interactions between
the threads.
. . .may be called by more than one thread at a time without requiring any other action on
the caller's part.
Given definitions like these, it's no wonder we find thread safety confusing! They sound sus-
piciously like “a class is thread-safe if it can be used safely from multiple threads.” You can't
really argue with such a statement, but it doesn't offer much practical help either. How do we
tell a thread-safe class from an unsafe one? What do we even mean by “safe”?
At the heart of any reasonable definition of thread safety is the concept of correctness . If our
definition of thread safety is fuzzy, it is because we lack a clear definition of correctness.
Correctness means that a class conforms to its specification . A good specification defines in-
variants constraining an object's state and postconditions describing the effects of its opera-
tions. Since we often don't write adequate specifications for our classes, how can we possibly
know they are correct? We can't, but that doesn't stop us from using them anyway once we've
convinced ourselves that “the code works”. This “code confidence” is about as close as many
of us get to correctness, so let's just assume that single-threaded correctness is something that
“we know it when we see it”. Having optimistically defined “correctness” as something that
can be recognized, we can now define thread safety in a somewhat less circular way: a class
is thread-safe when it continues to behave correctly when accessed from multiple threads.
Search WWH ::




Custom Search