Sub topic 2
Protecting Shared State with synchronized and Atomic Variables
Locking Shared Data
When two threads change the same variable at the same moment, updates can get lost. This bug is called a race condition. Java gives you two simple fixes.
The first fix is synchronized. It is a keyword that puts a lock on an object. Only one thread can hold the lock at a time, so the other thread waits its turn.
public class SyncCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
public static void main(String[] args) throws InterruptedException {
SyncCounter counter = new SyncCounter();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
counter.increment();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println(counter.get());
}
}This program always prints 200000.
The second fix is an atomic variable. An AtomicInteger is a number whose methods, such as incrementAndGet(), finish in one step that no other thread can interrupt. It needs no lock.
Thread Pools with ExecutorService
Creating a new thread for every job is slow and hard to manage. A thread pool is a group of threads that are reused for many tasks. An ExecutorService is a Java object that owns a pool. You hand it tasks, and it decides which thread runs each one. The Executors class has factory methods that build pools, such as Executors.newFixedThreadPool(2).
Getting Results with Callable and Future
A Runnable returns nothing. A Callable is a task that returns a value. When you submit a Callable, you get a Future back. A Future is a handle to a result that may not be ready yet. Calling get() waits until the result is ready.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Integer> answer = pool.submit(() -> 6 * 7);
pool.submit(() -> System.out.println("Runs on " + Thread.currentThread().getName()));
System.out.println("Result: " + answer.get());
} finally {
pool.shutdown();
}
}
}Shutting Down Cleanly
A pool's threads keep running until you stop them. If you never stop them, your program may never exit.
| Method | What it does |
|---|---|
| `shutdown()` | Stops new tasks and lets queued tasks finish |
| `awaitTermination(time, unit)` | Waits up to a time limit for tasks to finish |
| `shutdownNow()` | Tries to stop running tasks right away |
Exercise
Why does FutureDemo call pool.shutdown() inside a finally block?
Show answer
The finally block always runs, even when answer.get() throws an exception. That way the pool's threads always stop and the program can exit.