Java Reference
In-Depth Information
try {
Thread.sleep(200);
// then take a break
if(inTray.size() != 0)
break;
else
return;
} catch(InterruptedException e) {
System.out.println("Clerk " + ID + "\n" + e);
return;
}
}
theBank.doTransaction(inTray.remove(0));
if(Thread.interrupted()) {
System.out.println(
"Interrupt flag for Clerk " + ID + " set.
Terminating.");
return;
}
}
}
int ID;
private Bank theBank;
private List<Transaction> inTray =
// The in-tray holding
transactions
Collections.synchronizedList(new
LinkedList<Transaction>());
private int maxTransactions = 8;
// Maximum transactions in
the in-tray
}
Directory "UsingExecutors"
The
Clerk
constructor requires two arguments: an integer value that identifies a particular clerk and a
reference to the bank. Transactions are stored in a
List<Transaction>
collection that is the in-tray for
a clerk. The
List<Transaction>
object is created as a synchronized list from a
LinkedList<Transac-
tion>
object using a static utility method that is defined in the
Collections
class. Using a synchronized
list ensures that there is no concurrent access to the list by a transaction source thread, which involves
the
doTransaction()
method for a
Clerk
object, and a
Clerk
thread, which is the
run()
method for a
Clerk
object.
A clerk has an in-tray of a limited size specified by the
maxTransactions
member and does not accept
transactions if the in-tray is full. The
doTransaction()
method returns
true
if the transaction can be
added to the in-tray returns
false
otherwise. The
doTransaction()
method is also
synchronized
to
ensure that only one transaction source can communicate with a given clerk at one time.
In the
run()
method, a clerk sleeps if there are no transaction in
inTray
. Each time a clerk completes a
transaction, the
interrupted()
method is called to allow for cancellation of the
Clerk
thread.
Defining the Bank
The bank is defined by the
Bank
class, much as you have seen earlier: