Java Reference
In-Depth Information
Although this fixes the problem in that the account balance is now correct, the bank is still amazingly
inefficient. Each clerk is kicking his or her heels while another clerk is carrying out a transaction. At any
given time a maximum of one clerk is working. On this basis the bank could fire them all bar one and get
the same throughput. You can do better, as you see later.
Synchronizing Code Blocks
In addition to being able to synchronize methods on a class object, you can also specify a statement or a
block of code in your program as synchronized , which is more powerful because you specify which par-
ticular object is to benefit from the synchronization of the statement or code block, not just the object that
contains the code as in the case of a synchronized method. Here you can set a lock on any object for a given
statement block. When the block that is synchronized on the given object is executing, no other code block
or method that is synchronized on the same object can execute. To synchronize a statement, you just write:
synchronized( theObject )
statement ; // Synchronized with respect to theObject
No other statements or statement blocks in the program that are synchronized on the object theObject
can execute while this statement is executing. This applies even when the statement is a call to a method,
which may in turn call other methods. The statement here could equally well be a block of code between
braces. This is powerful stuff. Now you can lock a particular object while the code block that is working is
running.
To see precisely how you can use this in practice, let's create a modification of the last example. Let's up
the sophistication of our banking operation to support multiple accounts. To extend our example to handle
more than one account, you just need to make some changes to main() . You add one extra account to keep
the output modest, but you modify the code to handle any number of accounts.
TRY IT OUT: Handling Multiple Accounts
You can modify the code in main() that creates the account and sets the initial balance to create multiple
accounts as follows:
public class BankOperation3 {
public static void main(String[] args) {
int[] initialBalance = {500, 800};
// The
initial account balances
int[] totalCredits = new int[initialBalance.length]; // Two cr
totals
int[] totalDebits = new int[initialBalance.length]; // Two db
totals
int transactionCount = 20; //
Number of debits and credits
Search WWH ::




Custom Search