Java Reference
In-Depth Information
the number of processors in your PC. If you want to force overlapping debits and credits on the same
account, you can comment out the calculation of the value for select for the debit operation in the for
loop in main() . This modification is shown in bold:
// Generate a random account index for debit operation
// select = rand.nextInt(accounts.length);
totalDebits[select] += amount; // Keep total debit tally
This makes the debit transaction apply to the same account as the previous credit, so the transactions are
always contending for the same account.
Of course, this is not the only way of getting the operations to overlap. Another approach would be to
equip accounts with methods to handle their own credit and debit transactions and declare these as syn-
chronized methods.
Although testing that you have synchronization right is relatively easy in our example, in general it is
extremely difficult to be sure you have adequately tested a program that uses threads. Getting the design
right first is essential, and you really have no substitute for careful design in programs that have multiple
threads (or indeed any real-time program that has interrupt handlers). You can never be sure that a real-
world program is 100 percent correct — only that it works correctly most of the time!
Deadlocks
Because you can synchronize code blocks for a particular object virtually anywhere in your program, there's
potential for a particularly nasty kind of bug called a deadlock . This involves a mutual interdependence
between two threads. One way this arises is when one thread executes some code synchronized on a giv-
en object, theObject , say, and then needs to execute another method that contains code synchronized on
another object, theOtherObject , say. Before this occurs, though, a second thread executes some code syn-
chronized to theOtherObject and needs to execute a method containing code synchronized to the first ob-
ject, theObject . This situation is illustrated in Figure 16-8 .
FIGURE 16-8
 
 
Search WWH ::




Custom Search