Java Reference
In-Depth Information
Consider a method that contains a sequence of operations that, if interrupted part‐
way through, could leave an object in an inconsistent or illegal state. If this illegal
state was visible to another object, incorrect code behavior could occur.
For example, consider an ATM or other cash-dispensing machine:
public class Account {
private double balance = 0.0 ; // Must be >= 0
// Assume the existence of other field (e.g. name) and methods
// such as deposit(), checkBalance() and dispenseNotes()
public Account ( double openingBal ) {
balance = openingBal ;
public boolean withdraw ( double amount ) {
if ( balance >= amount ) {
try {
Thread . sleep ( 2000 ); // Simulate risk checks
} catch ( InterruptedException e ) {
return false ;
balance = balance - amount ;
dispenseNotes ( amount );
return true ;
return false ;
The sequence of operations that happens inside withdraw() can leave the object in
an inconsistent state. In particular, after we've checked the balance, a second thread
could come in while the first was sleeping in simulated risk checks, and the account
could be overdrawn, in violation of the constraint that balance >= 0 .
This is an example of a system where the operations on the objects are single-
threaded safe (because the objects cannot reach an illegal state ( balance < 0 ) if
called from a single thread), but not concurrently safe.
To allow the developer to make code like this concurrently safe, Java provides the
synchronized keyword. This keyword can be applied to a block or to a method, and
when it is used, the platform uses it to restrict access to the code inside the block or
y d
Because synchronized surrounds code, many developers are
led to the conclusion that concurrency in Java is about code.
Some texts even refer to the code that is inside the synchron‐
ized block or method as a critical section and consider that to
be the crucial aspect of concurrency. This is not the
case; instead, it is the inconsistency of data that we must guard
against, as we will see.
Search WWH ::

Custom Search