Synchronized method
One or more methods of a class can be declared to be synchronized.
When a thread calls an object's synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes).
Here is an example of a BankAccount class that uses synchronized methods to ensure that deposits and withdrawals cannot be performed simultaneously, and to ensure that the account balance cannot be read while either a deposit or a withdrawal is in progress.
(To keep the example simple, no check is done to ensure that a withdrawal does not lead to a negative balance.)
public class BankAccount {
private double balance;
// Constructor: set balance to given amount
public BankAccount( double initialDeposit ) {
balance = initialDeposit;
}
public synchronized double Balance( ) {
return balance;
}
public synchronized void Deposit( double deposit ) {
balance += deposit;
}
public synchronized void Withdraw( double withdrawal ) {
balance -= withdrawal;
}
}
Note: that the BankAccount's constructor is not declared to be synchronized.
That is because it can only be executed when the object is being created, and no other method can be called until that creation is finished.
Synchronized block
There are cases where we need to synchronize a group of statements, we can do that using synchrozed statement.
Example
synchronized ( B ) {
if ( D > B.Balance() )
{
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.