Synchronised Methods
This method extends the example in the last lecture.
Java uses the American spelling: synchronized
.
Synchronised Method
class Buffer {
private int v;
private volatile boolean empty = true;
public synchronized void insert (int x) {
while (!empty)
; // null loop
empty = false;
v = x;
}
public synchronized int remove() {
while (empty)
; // null loop
empty = true;
return v;
}
}
Every object has a lock associated with it.
- When a thread called a
synchronized
method, it gains exclusive control of the lock. - All other threads calling
synchronized
methods on that object must idle in an entry set. - When the thread with control exits the
synchronized
method, the lock is released.- The JVM can then select an arbitrary thread from the entry set to be granted control of the block.
Replace Spinlock with wait()
and notify()
class Buffer {
private int v;
private volatile boolean empty = true;
public synchronized void insert (int x) {
while (!empty) {
try {
wait();
}
catch (InterruptedException e) {}
}
empty = false;
v = x;
notify();
}
// similarly for remove()
}
- The
wait()
call:- Stops thread execution.
- Moves the calling thread to the wait set.
- The
notify()
call:- Moves an arbitrary thread from the wait set back to the entry set.
- Depends on particular JVM implementation.
- the
notifyAll()
call:- Tells all thread in the wait set that a resource is available.
-
Threads compete for access in the same way.
The first one to call a
synchronized
method gets the access.
Entry & Wait Sets
flowchart BT
subgraph Runnable["Entry Set(Runnable)"]
a
b
c
end
Runnable -->|synchronized call| Lock
subgraph Lock[Object Lock]
d1["Owner (d)"]
end
Lock -->|wait| Blocked
d1 -->|notify| d
d --> Runnable
subgraph Blocked["Wait Set (Blocked)"]
d
e
f
end
Key Java Multi-Threaded Concepts
The following concepts are useful for multi-threaded programs:
Thread
objects.run()
method and thestart()
method call.volatile
andsynchronized
keywords.yeild()
,wait()
andnotify()
method calls.