Java Reference
In-Depth Information
periodic snapshots of its progress, so that it does not have to start again from the beginning if
it crashes or must be stopped. You might choose to do this with a TimerTask that goes off
every ten minutes, saving the program state to a file.
Since the TimerTask will be called from another thread (one managed by Timer ), any
data involved in the snapshot is now accessed by two threads: the main program thread and
the Timer thread. This means that not only must the TimerTask code use synchronization
when accessing the program state, but so must any code path in the rest of the program that
touches that same data. What used to require no synchronization now requires synchroniza-
tion throughout the program.
When a variable is guarded by a lock—meaning that every access to that variable is per-
formed with that lock held—you've ensured that only one thread at a time can access that
variable. When a class has invariants that involve more than one state variable, there is an
additional requirement: each variable participating in the invariant must be guarded by the
same lock. This allows you to access or update them in a single atomic operation, preserving
the invariant. SynchronizedFactorizer demonstrates this rule: both the cached num-
ber and the cached factors are guarded by the servlet object's intrinsic lock.
For every invariant that involves more than one variable, all the variables involved in that
invariant must be guarded by the same lock.
If synchronization is the cure for race conditions, why not just declare every method syn-
chronized ? It turns out that such indiscriminate application of synchronized might be
either too much or too little synchronization. Merely synchronizing every method, as Vect-
or does, is not enough to render compound actions on a Vector atomic:
This attempt at a put-if-absent operation has a race condition, even though both contains
and add are atomic. While synchronized methods can make individual operations atomic,
additional locking is requiredwhen multiple operations are combined into a compound action.
(See Section 4.4 for some techniques for safely adding additional atomic operations to thread-
Search WWH ::




Custom Search