Java Reference
In-Depth Information
Synchronization makes the interleaved execution example work: If the
code is in a synchronized method, then when the second thread at-
tempts to access the object while the first thread is using it, the second
thread is blocked until the first one finishes.
For example, if the BankAccount class were written to live in a multith-
readed environment it would look like this:
public class BankAccount {
private long number; // account number
private long balance; // current balance (in cents)
public BankAccount(long initialDeposit) {
balance = initialDeposit;
}
public synchronized long getBalance() {
return balance;
}
public synchronized void deposit(long amount) {
balance += amount;
}
// ... rest of methods ...
}
Now we can explain what is "appropriate" in synchronizing methods.
The constructor does not need to be synchronized because it is executed
only when creating an object, and that can happen in only one thread
for any given new object. Constructors, in fact, cannot be declared syn-
chronized .
The balance field is defended from unsynchronized modification by the
synchronized accessor methods. If the value of a field can change, its
value should never be read at the same time another thread is writing
it. If one thread were reading the value while another was setting it, the
read might return an invalid value. Even if the value were valid, a get-
modifyset sequence requires that the value not change between being
read and being set, otherwise the set value will be wrong. Access to the
 
Search WWH ::




Custom Search