img
.
Chapter 6. Synchronization
Synchronization Issues
Synchronization Variables
APIs Used in This Chapter
The Class java.lang.Object
The Class Extensions.Semaphore
The Class Extensions.Mutex
The Class Extensions.ConditionVar
In which the reader is led on a hunt for the intimidating synchronization variable and discovers
that it is not actually as frightening as had been thought. Programs illustrating the basic use of the
POSIX and Java primitives are shown.
Synchronization Issues
To write any kind of concurrent program, you must be able to synchronize the different threads
reliably. Failure to do so will result in all sorts of ugly, messy bugs. Without synchronization, two
threads will start to change some data at the same time; one will overwrite the other. To avoid this
disaster, threads must reliably coordinate their actions.
In Code Example 6-1, your bank has one thread running, calculating the dividends on your bank
account. If you're like me, that's about $10 @ 1%, giving a newBalance of $10.10. At exactly
this instant, the end of the month arrives and a second thread decides to deposit your paycheck. As
a well-paid, highly skilled programmer, that's probably about $20,000. The thread deposits the
check and updates your account to $20,010. One microsecond later the first thread completes its
work, overwriting your bank balance with $10.10. Too bad.
Example 6-1 Why Synchronization Is Necessary
Thread 1
Thread 2
temp = your.bankBalance;
temp = your.bankBalance;
dividend = temp * InterestRate;
newBalance = deposit + temp;
newBalance = dividend + temp;
your.bankBalance = newBalance;
your.bankBalance = newBalance;
Atomic Actions and Atomic Instructions
Implementation of synchronization requires the existence of an atomic test and set instruction in
hardware. This is true for both uniprocessor and multiprocessor machines. Because threads can be
preempted at any time, between any two instructions, you must have such an instruction. Sure,
there might be only a 10-ns window for disaster to strike, but you still want to avoid it.
A test and set instruction tests (or just loads into a register) a word from memory and sets it to
some value (typically, 1), all in one instruction, with no possibility of anything happening in
between the two halves (e.g., an interrupt or a write by a different CPU). If the value of the target
word is 0, it gets set to 1 and you are considered to have ownership of the lock. If it already is 1, it
gets set to 1 (i.e., no change) and you don't have ownership. All synchronization is based upon the
existence of this instruction.
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home