Java Reference
In-Depth Information
Chapter 2. Thread Safety
Perhaps surprisingly, concurrent programming isn't so much about threads or locks, any more
than civil engineering is about rivets and I-beams. Of course, building bridges that don't fall
down requires the correct use of a lot of rivets and I-beams, just as building concurrent pro-
grams require the correct use of threads and locks. But these are just mechanisms —means to
an end. Writing thread-safe code is, at its core, about managing access to state , and in particu-
lar to shared, mutable state .
Informally, an object's state is its data, stored in statevariables such as instance or static fields.
An object's state may include fields from other, dependent objects; a HashMap 's state is par-
tially stored in the HashMap object itself, but also in many Map.Entry objects. An object's
state encompasses any data that can affect its externally visible behavior.
By shared , we mean that a variable could be accessed by multiple threads; by mutable , we
mean that its value could change during its lifetime. We may talk about thread safety as if it
were about code , but what we are really trying to do is protect data from uncontrolled concur-
rent access.
Whether an object needs to be thread-safe depends on whether it will be accessed from mul-
tiple threads. This is a property of how the object is used in a program, not what it does . Mak-
ing an object thread-safe requires using synchronization to coordinate access to its mutable
state; failing to do so could result in data corruption and other undesirable consequences.
Whenever more than one thread accesses a given state variable, and one of them might write
to it, they all must coordinate their access to it using synchronization. The primary mechan-
ism for synchronization in Java is the synchronized keyword, which provides exclusive
locking, but the term “synchronization” also includes the use of volatile variables, explicit
locks, and atomic variables.
You should avoid the temptation to think that there are “special” situations in which this rule
does not apply. A program that omits needed synchronization might appear to work, passing
its tests and performing well for years, but it is still broken and may fail at any moment.
If multiple threads access the same mutable state variable without appropriate synchronization,
your program is broken . There are three ways to fix it:
Don't share the state variable across threads;
Search WWH ::




Custom Search