Concurrency I

Overview

  • Course: ECM2414 – Software Development
  • Topic: Concurrency I
  • Session: T1: W2-L1
  • Instructor: Prof. Solomon Oyelere
  • Department: Computer Science, University of Exeter

What is Concurrency?

Definition: The ability to perform multiple processes at the same time, including the potential interaction between them.

  • Multiple tasks simultaneously = Parallelism
  • Essential for modern computing systems

Why Use Concurrency?

  1. Program Interaction: Allowing programs to interact with other systems/users
  2. Multi-core Systems: Taking advantage of multiple processor cores
  3. Performance: Better resource utilization

Threads vs Processes

Threads

  • Lightweight processes
  • Threads exist within a process
  • Shared memory space between threads in same process

Why Threads Instead of Separate Programs?

  • Shared Memory Space: Easier data sharing
  • Lower Overhead: Less resource intensive than separate processes
  • Better Communication: Faster inter-thread communication

Visual Representation

Process
├── Thread 1 (Local Memory 1, Local Variables)
├── Thread 2 (Local Memory 2, Local Variables)
├── Thread 3
└── Thread 4

Multi-threading vs Multi-tasking

Multi-threading

  • Processing: Shared within same process
  • Memory Space: Shared memory space between threads
  • Threads can run:
    • Virtually on single processor (time-slicing)
    • Actually on multi-core processor (true parallelism)

Multi-tasking

  • Processing: Separate processes
  • Memory Space: Each process has separate memory space

System Architecture Examples

Single Core System

OS → Browser → Email → AntiVirus
(Sequential execution with time-slicing)

Multi-Core System

Core 1: OS, Browser
Core 2: Email, AntiVirus
(True parallel execution)

New Challenges with Multi-threading

1. Nondeterminism

Problem: Unpredictable execution order

Sequential Execution

Time → Task 1 → Task 2 → Task 3 → Task 4

Multi-threaded Execution

Time → Task 1, Task 2
     → Task 3, Task 4
     (Order not guaranteed)

2. Liveness Issues

Previous Concern: Safety - code performs correctly
New Concern: Liveness - code performs correctly in time

Liveness Requirements:

  • Not just that bad things don’t happen
  • Good things DO happen eventually
  • Need to determine acceptable level of “eventually”

Creating Threads in Java

Method 1: Extending Thread Class

public class HelloThread extends Thread { 
    public void run() {
        System.out.println("Hello from a thread!");
    }
    
    public static void main(String args[]) {
        (new HelloThread()).start();
    }
}

Method 2: Implementing Runnable Interface

public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }
    
    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

Which Method to Choose?

Extending Thread: Simple to implement but has drawbacks
Implementing Runnable: More flexible (can extend other classes)

Best Practice: Use Runnable interface (allows class to extend other classes)

Thread Lifecycle Methods

Package java.lang
public class Thread implements Runnable {
    public void start();                    // Start thread execution
    public void run();                      // Thread's main execution method
    public void stop();                     // deprecated (race condition)
    public void resume();                   // deprecated  
    public void suspend();                  // deprecated
    public static void sleep(long millis);  // Pause execution
    public static void sleep(long millis, int nanos);
    public boolean isAlive();               // Check if thread is active
    public void interrupt();                // Request thread interruption
    public boolean isInterrupted();         // Check interruption status
    public static boolean interrupted();    // Clear interruption status
    public void join();                     // Wait for thread completion
}

Stopping Threads Safely

Method 1: Setting a Flag

public void run() {
    while (!done) {
        // Thread work here
    }
}
  • Loop exits when done is set to true
  • Thread stops on next iteration

Method 2: Interrupting

public void run() {
    while (!isInterrupted()) {
        // Thread work here
    }
}
  • When isInterrupted() is called, thread will stop
  • Exception: If thread is sleeping/waiting, throws InterruptedException

Race Conditions

Definition

When two or more threads try to access/change data simultaneously, causing unpredictable results.

Example Problem

public class MyCounter {
    private int count = 0;
    
    public void addTwo() {
        count = count + 2;
    }
    
    public void subtractTwo() {
        count = count - 2;
    }
    
    public int countValue() {
        return count;
    }
}

Race Condition Scenario

  1. Thread 1 (addTwo): Retrieve counter (0)
  2. Thread 2 (subtractTwo): Retrieve counter (0)
  3. Thread 1: Calculate result (0 + 2 = 2)
  4. Thread 2: Calculate result (0 - 2 = -2)
  5. Thread 1: Store result (count = 2)
  6. Thread 2: Store result (count = -2)

Expected Result: 0
Actual Result: -2 (incorrect!)

Synchronization

Method Synchronization

Solution: Add synchronized keyword to methods

public class MyCounter {
    private int count = 0;
    
    public synchronized void addTwo() {
        count = count + 2;
    }
    
    public synchronized void subtractTwo() {
        count = count - 2;
    }
    
    public synchronized int countValue() {
        return count;
    }
}

How it works:

  • When one thread executes a synchronized method, all other threads invoking synchronized methods on the same object block and suspend until the first thread completes.

Statement Synchronization

Synchronize specific code blocks instead of entire methods:

public void doSomeSynchronisedStuff() {
    // Code here is NOT synchronized
    
    synchronized (this) {
        // Code here IS synchronized
        // ...
    }
    
    // Code here is NOT synchronized either
}

Atomic Actions

Definition

Atomic actions are self-contained operations that cannot be stopped in the middle.

  • They either happen completely or don’t happen at all

Java Atomic Access

Atomic operations in Java:

  • Primitive data types: byte, short, int, long, float, double, boolean, char
  • Reads and writes are atomic for most primitives (except long and double)
  • All variables declared volatile (including long and double)

Example

volatile long atomicLong;     // This is atomic
long regularLong;            // This is NOT atomic (can be split)

Key Concepts Summary

Thread Creation

  1. Extend Thread class (simple but limiting)
  2. Implement Runnable interface (flexible, preferred)

Thread Safety Issues

  1. Nondeterminism - unpredictable execution order
  2. Race conditions - simultaneous data access problems
  3. Liveness - ensuring progress happens eventually

Solutions

  1. Synchronization - synchronized keyword
  2. Atomic operations - indivisible operations
  3. Proper thread termination - flags or interruption

Exercise Answer

Question: Why does multi-threading have non-deterministic behaviors?

Answer: A. That is because we (programmers) don’t have any control of which thread will be run at when.

Explanation:

  • A. Correct: Thread scheduling is handled by the OS, not programmers
  • B. Incorrect: Threads don’t control their own scheduling
  • C. Partially correct: OS does schedule threads, but this explains the mechanism, not why it’s non-deterministic from programmer’s perspective

The operating system scheduler determines when each thread runs, creating unpredictable execution patterns that programmers cannot directly control.


Tags

java concurrency threading synchronization raceconditions multithreading softwaredevelopment