Concurrency II
Overview
- Course: ECM2414 – Software Development
- Topic: Concurrency II
- Session: T1: W2-L2
- Instructor: Prof. Solomon Oyelere
- Department: Computer Science, University of Exeter
Threading Issues
1. Deadlock
Definition: A situation where two or more threads are blocked forever, each waiting for the other to release a resource.
Deadlock Scenario
Thread 1 ←→ Resource 1
↓ ↑
↓ ↑
Resource 2 ←→ Thread 2
- Thread 1 holds Resource 1, needs Resource 2
- Thread 2 holds Resource 2, needs Resource 1
- Result: Both threads wait indefinitely
2. Starvation
Definition: A thread can’t gain regular access to shared resources because other threads frequently monopolize the object’s methods.
Starvation Scenario
Object (with synchronized methods)
├── Method 1 ←── Greedy Thread (frequent access)
└── Method 2 ←── Starved Thread (blocked access)
Problem: Greedy thread continuously accesses synchronized methods, preventing starved thread from executing.
3. Livelock
Definition: Similar to deadlock, but threads are too busy responding to each other to do actual work.
Corridor Example
Man: Move left → Woman: Move right
Man: Move right ← Woman: Move left
(Continuous movement, no progress)
Characteristics:
- Threads are not blocked (unlike deadlock)
- Threads are active but unproductive
- No forward progress is made
Thread Management Methods
From Thread Class
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedExceptionFrom Object Class
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()Note: sleep, join, and wait have overloaded versions.
Thread Notification: wait() and notify()
Java Monitor Concept
Every Java object has a monitor:
- Monitor = Lock + Set of waiting threads
- Used for thread coordination and communication
wait() Method
Basic Syntax
void wait() // Wait indefinitely
void wait(long timeStep) // Wait for specified milliseconds
void wait(long timeStep, int nanos) // Wait with nanosecond precisionRequirements
- Must be called from synchronized method/block
- Releases the lock while waiting
- Thread waits for a condition to occur
Example Usage
public synchronized void announceBob() {
while(!bob) {
try {
wait(); // Release lock and wait
} catch (InterruptedException e) {}
}
System.out.println("We have bob!!");
}notify() and notifyAll() Methods
notify()
- Wakes up one waiting thread
- Must be called from synchronized method/block
notifyAll()
- Wakes up all waiting threads
- Must be called from synchronized method/block
Example Usage
public synchronized void notifyBob() {
bob = true;
notifyAll(); // Wake up all waiting threads
}
// OR
public synchronized void notifyBob() {
bob = true;
notify(); // Wake up one waiting thread
}sleep() Method
Example: SleepyThreads
public class SleepyThreads {
public static void main(String[] args) {
SleepyRunnable sr = new SleepyRunnable();
Thread uno = new Thread(sr, "Jose");
Thread dos = new Thread(sr, "Pablo");
Thread tres = new Thread(sr, "Juan");
uno.start();
dos.start();
tres.start();
}
}
class SleepyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running.");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) { }
}
}
}What is Guaranteed?
- Each thread will print its message
- Each thread will sleep for 2 seconds between iterations
- Order of execution is NOT guaranteed (non-deterministic)
Wait vs Sleep Comparison
| Aspect | wait() | sleep() |
|---|---|---|
| Synchronization | Must occur in synchronized block | No synchronization required |
| Lock Handling | Releases the monitor (lock) | Retains the monitor (lock) |
| Timeslice | Doesn’t sacrifice timeslice | Sacrifices remainder of timeslice |
| Waking Up | Woken by notify()/notifyAll() | Only woken by interruption |
| Purpose | Thread communication/coordination | Simple pause/delay |
Thread Lifecycle
States and Transitions
[New] --start()--> [Runnable] --OS dependent--> [Running] --run() returns--> [Dead]
↑ ↓ ↓
| [Sleeping] ←--sleep()--┘
| ↓
| sleep time up
| ↓
| [Waiting] ←--wait()--┘
| ↓
└--notify()/notifyAll()---┘
↓
[Blocking] ←--yield()--┘
State Descriptions
- New: Thread instance created but
start()not called - Runnable: Thread eligible to run, waiting for CPU
- Running: Thread actively executing
- Sleeping: Thread paused for specified time
- Waiting: Thread waiting for notification
- Blocking: Thread blocked waiting for resource/lock
- Dead: Thread completed execution (
run()returned)
yield() Method
Purpose
- Causes currently executing thread to pause
- Allows other threads of same or higher priority to execute
Behavior
Thread.yield();- If no other threads of same priority need execution → current thread continues
- Identifies current thread as doing something not particularly important
- Hint to scheduler, not guaranteed behavior
join() Method
Purpose
Allows one thread to wait for completion of another thread.
Usage
Thread t = new Thread(someRunnable);
t.start();
t.join(); // Current thread waits for 't' to completeCharacteristics
- Similar to
sleep(), responds to interrupts - Exits with
InterruptedExceptionif interrupted - Blocks calling thread until target thread completes
Explicit Locking
Traditional Synchronization Limitation
- In
synchronized, the lock exists but isn’t visible - Limited control over lock behavior
Lock Interface Benefits
import java.util.concurrent.locks.*;
public class ThreadsLectureExample {
private Lock myLock = new ReentrantLock();
public void doThingsIWantToLock() {
try {
myLock.lock(); // Explicit lock acquisition
// Critical section code here
} finally {
myLock.unlock(); // MUST explicitly release
}
}
}Advanced Lock Features
- Two or more objects can share a lock
- One object can have multiple locks
- Manual control over lock acquisition/release
- More flexible than synchronized blocks
Key Differences: synchronized vs Lock
| Feature | synchronized | Lock Interface |
|---|---|---|
| Lock Release | Automatic | Manual (must use finally) |
| Flexibility | Limited | High |
| Visibility | Hidden | Explicit |
| Sharing | Object-bound | Can be shared |
Exercise: Thread Lifecycle Statements
Question: Choose the correct statement(s) about thread lifecycle:
A. Thread scheduler selects a thread to go from runnable state to running state. In the running state, the thread starts executing by entering the run() method.
B. A thread is considered dead when its run() method completes.
C. When the instance of a thread is created using the new operator it is in the new state, but the start() method has not been invoked on the thread yet, thread is not eligible to run yet.
D. When the start() method is called on a thread it enters the runnable state.
Answer: All statements (A, B, C, D) are CORRECT
Explanation:
- A. Correct: Scheduler moves threads from runnable → running, execution begins in
run() - B. Correct: Thread dies when
run()method completes - C. Correct: New threads exist but aren’t eligible until
start()is called - D. Correct:
start()moves thread from new → runnable state
Key Takeaways
Threading Problems
- Deadlock: Mutual waiting, no progress
- Starvation: One thread monopolizes resources
- Livelock: Active but unproductive threads
Thread Communication
- wait()/notify(): Coordinate thread execution
- join(): Wait for thread completion
- yield(): Hint to scheduler for thread switching
- sleep(): Pause thread execution
Synchronization Evolution
- synchronized: Simple but limited
- Lock interface: Explicit, flexible control
Summary
This lecture covered advanced threading concepts including common problems (deadlock, starvation, livelock) and solutions (wait/notify, join, yield, explicit locks). These tools provide better control over thread coordination and help design more robust concurrent applications.
Next: Final lecture on threading (Concurrency III)
Tags
java concurrency threading deadlock starvation livelock synchronization waitnotify threadlifecycle softwaredevelopment