Concurrency III
Overview
- Course: ECM2414 – Software Development
- Topic: Concurrency III
- Session: T1: W3-L1
- Instructor: Prof. Solomon Oyelere
- Department: Computer Science, University of Exeter
Data Issues with Threads
Previously Covered Execution Issues
- Race Conditions: Multiple threads accessing shared data
- Livelock: Threads active but unproductive
- Deadlock: Threads waiting for each other indefinitely
New Focus: Data Freshness
Problem: Ensuring threads access fresh (up-to-date) data
Issue: Stale data can lead to significant problems
Memory Issues - Visibility
The Problem
Threads may not see the most recent changes made by other threads due to:
- CPU caching
- Compiler optimizations
- Memory model complexities
Result: Threads working with outdated/stale data
Counter Example Recap
Simple Counter Issues
class Counter {
private int c = 0;
public void increment() {
c++; // NOT atomic!
}
public void decrement() {
c--; // NOT atomic!
}
public int value() {
return c;
}
}Why c++ is NOT Atomic
A simple c++ statement involves three operations:
- Get current value of
c - Add 1 to the value
- Set the new value back to
c
Problem: Another thread can interfere between these steps!
Atomic Variables
Purpose
Java provides java.util.concurrent.atomic package for variables that support atomic operations on single variables.
Available Atomic Types
AtomicIntegerAtomicLongAtomicBooleanAtomicReference- And more…
Common Atomic Methods
All Atomic Types Implement:
set(newValue) // Set value atomically
get() // Get current value
getAndSet(newValue) // Set new value, return old value
compareAndSet(expected, update) // Set if current equals expected
weakCompareAndSet(expected, update) // Weaker version of compareAndSetAtomicInteger and AtomicLong Also Implement:
incrementAndGet() // Atomically increment, return updated value
decrementAndGet() // Atomically decrement, return updated value
getAndIncrement() // Atomically increment, return original value
getAndDecrement() // Atomically decrement, return original value
addAndGet(delta) // Atomically add delta, return updated value
getAndAdd(delta) // Atomically add delta, return original valueMethod Patterns
XAndGet(): Atomically performs X operation and returns updated valuegetAndX(): Atomically performs X operation and returns original value
compareAndSet() Method
boolean compareAndSet(expectedValue, newValue)- Atomically sets value to
newValueif current value equalsexpectedValue - Returns
trueif successful,falseotherwise - Lock-free programming technique
Synchronization vs Atomic Variables
Traditional Synchronized Approach
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}Atomic Variables Approach
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}Comparison
| Aspect | Synchronized | Atomic Variables |
|---|---|---|
| Performance | Can block threads | Lock-free, better performance |
| Complexity | Simple syntax | Specialized methods |
| Scope | Can protect multiple operations | Single variable operations |
| Deadlock Risk | Possible | None (lock-free) |
Volatile & Data Freshness
The volatile Keyword
Purpose: Tells compiler not to optimize accesses and forces next read to see the last write.
Problem Example
class LoopMayNeverEnd {
boolean done = false; // NOT volatile
void work() {
while (!done) {
// do work - may loop forever!
}
}
void stopWork() {
done = true; // Other thread may not see this change
}
}Issue: If one thread calls work() and another calls stopWork(), the loop may never see the change to done.
Solution with volatile
class LoopWillEnd {
volatile boolean done = false; // NOW volatile
void work() {
while (!done) {
// do work - will eventually stop
}
}
void stopWork() {
done = true; // Change will be visible to all threads
}
}volatile Characteristics
- Forces compiler to prevent optimization
- Checks variable every time it’s accessed
- More expensive than regular variables
- Less expensive than synchronization
- No atomicity guarantee for compound operations
Publishing & Escape
Publishing Definition
Publishing an object = Making it available outside its current scope
Examples:
- Storing a reference where other code can find it
- Making it a non-private attribute
- Returning from non-private method
Escape Definition
Object escape = Object published when it should NOT have been
Examples:
- Accessing uninitialized state variables
- Exposing internal data structures
Unsafe Publishing Example
class UnsafeStates {
private String[] states = new String[] {
"AK", "AL", ...
};
public String[] getStates() {
return states; // UNSAFE! Direct reference to internal array
}
}Problem: Caller can modify the internal states array!
Safe Publishing Solution
class SafeStates {
private String[] states = new String[] {
"AK", "AL", ...
};
public String[] getStates() {
return states.clone(); // SAFE! Return copy
}
}Publishing Chain Rule
Any object reachable from a published object through non-private field references has also been published.
Default Publishing Policy
- By default: Don’t publish objects unless necessary
- If publishing: Confirm thread-safe nature of the publishing mechanism
Thread Confinement
Definition
Thread confinement = Restricting data access to a single thread
Key Principle
“If data doesn’t need to be shared, confine it to a single thread”
Benefits
- Simplest way to ensure thread safety
- No synchronization required
- Better performance (no locking overhead)
- No race conditions possible
Implementation
- Thread confinement is an element of program design
- Use local variables when possible
- Pass data as method parameters rather than sharing state
Lambda Expressions (Java 8)
Introduction
- Java 8.0 introduced Lambda Expressions (2014)
- First introduction of functional programming aspects to Java
- Single largest upgrade to Java language ever (including generics)
What are Lambda Expressions?
Lambda expression = Block of code that can be passed around between objects
Previously: Could only pass objects or primitives between objects
Now: Can pass behavior (code blocks) directly
Lambda Syntax
(arguments) -> {body}Rules:
- Zero or more arguments allowed
- Argument types can be declared or inferred
- Single inferred argument: No parentheses needed
- Single expression body: No curly brackets needed
Lambda Examples
// With explicit types and multiple statements
(int x, int y) -> {return x * y;}
// Single parameter, inferred type, single statement
s -> {System.out.println(s);}
// Simplified single statement (no braces)
s -> System.out.println(s)
// No parameters
() -> System.out.println("Hello from a Lambda expression")
// Multiple parameters, inferred types
(a, b) -> a + bCalculator Example with Lambdas
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator myApp = new Calculator();
// Lambda expressions implementing IntegerMath
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " +
myApp.operateBinary(40, 2, addition));
System.out.println("20 - 10 = " +
myApp.operateBinary(20, 10, subtraction));
}
}Key Benefits of Lambdas
- More concise code - less boilerplate
- Better readability - behavior defined inline
- Functional programming capabilities
- Easier parallel processing with streams
Exercise: Publishing Examples
Question: Which example(s) below show a publishing example?
A. By storing a reference to it where other code can find it.
B. Returning it from a non-private method.
C. Passing it to a method in another class.
D. Storing it in a private method.
Answer: A, B, and C are correct
Explanation:
- A. Correct: Storing reference makes object accessible to other code
- B. Correct: Non-private methods expose objects outside current scope
- C. Correct: Passing to another class makes object available outside scope
- D. Incorrect: Private methods don’t publish objects outside current scope
Section Summary: Complete Concurrency Coverage
Nested Classes (Previous Lecture)
- Inner classes, anonymous classes for better encapsulation
- Useful in threading for closely coupled classes
Concurrency Topics Covered
-
Thread Creation & Management
- Extending Thread vs Implementing Runnable
- Thread lifecycle and states
-
Execution Issues
- Race conditions, deadlock, livelock, starvation
- Synchronization and locks
-
Data Access Issues
- Memory visibility problems
- Atomic variables for lock-free programming
- Volatile keyword for visibility guarantees
-
Design Patterns
- Publishing and escape prevention
- Thread confinement strategies
Lambda Expressions
- Functional programming in Java
- Code as data - passing behavior between objects
- Foundation for modern Java features (Streams, etc.)
Key Takeaways
Thread Safety Strategies
- Synchronization: Traditional approach with performance cost
- Atomic Variables: Lock-free, better performance for single variables
- Volatile: Visibility guarantees without full synchronization
- Thread Confinement: Avoid sharing when possible
Modern Java Features
- Lambda Expressions: Enable functional programming paradigms
- Better API Design: Pass behavior instead of objects
Resources
Next Topics
Next lecture: Version Control Systems
Tags
java concurrency atomicvariables volatile memoryvisibility publishing escape threadconfinement lambdaexpressions functionalprogramming softwaredevelopment