Professional Documents
Culture Documents
Mutual Exclusion
• Simultaneous reading and setting of a value
by different threads
• May not be atomic
• One object needs to lock others out until it is
finished
• Can be done at the
1. class level
2. method level
3. on a block of code
The keyword synchronized
• This keyword obtains a mutex (mutual exclusion)
lock for the executing thread on the named
object.
• The code is then executed, and the lock is
released.
• If another object already holds the lock, the
thread is suspended until the lock is released.
• Lock-competing threads are queued.
Java and synchronization
• Java programmers don’t need to do the
low level details of creating, acquiring,
and releasing locks
– Unix semaphores, locks
• Specify the portion of code (critical
section) for mutual exclusion, and the
object that must be exclusively locked
• The region of code must be as small as
possible
Java synchronization techniques
• Object as a lock
SetPressure.SafetyLimit - 15)
{
...
}
...
}
Object as a Lock
• Any object can serve as a lock
– Separate object: Object myLock = new Object();
– Current instance: the this object
synchronized(myLock) {
// code here
}
13
Example using synchronized methods
On-line banking
Several entities can access account potentially simultaneously
(maybe a joint account, maybe automatic debits, …)
• deposit()
• withdraw()
• enquire()
14
Create three threads, one for each entities
class InternetBankingSystem {
public static void main(String [] args ) {
Account accountObject = new Account ();
Thread t1 = new Thread(new MyThread(accountObject));
Thread t2 = new Thread(new YourThread(accountObject));
Thread t3 = new Thread(new HerThread(accountObject));
t1.start();
t2.start();
t3.start();
} // end main()
}
15
Shared account
class MyThread implements Runnable {
Account account;
public MyThread (Account s) { account = s;}
public void run() { account.deposit(); }
} // end class MyThread
}
18
Synchronized Statements
Example
19
atomic action
20
Coordinating threads
Wait/notify mechanism
Sometimes need a thread to stop running and wait for an
event before continuing.
22
synchronized Statement
• Every object has a lock associated with it.