Skip to content
UoL CS Notes

Synchronised Methods

COMP124 Lectures

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.

  1. When a thread called a synchronized method, it gains exclusive control of the lock.
  2. All other threads calling synchronized methods on that object must idle in an entry set.
  3. 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:
    1. Stops thread execution.
    2. Moves the calling thread to the wait set.
  • The notify() call:
    1. Moves an arbitrary thread from the wait set back to the entry set.
    2. Depends on particular JVM implementation.
  • the notifyAll() call:
    1. Tells all thread in the wait set that a resource is available.
    2. 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 the start() method call.
  • volatile and synchronized keywords.
  • yeild(), wait() and notify() method calls.