Core Java Advanced LiveLessons

Concurrent Programming

Copyright © Cay S. Horstmann 2016

Use executors to run tasks concurrently

Running Tasks

Executors

Running Tasks Concurrently

lesson04/runnable

Callables

Futures

More about Executor Services

lesson04/callable

Understand the risks of concurrent execution

Concurrency—What Could Possibly Go Wrong?

Sharing Variables

lesson04/visibility

Visibility

Ensuring Visibiliity

Race Conditions

lesson04/raceCondition/RaceConditionDemo

Race Conditions

lesson04/raceCondition/RaceConditionDemo2

Strategies for Safe Concurrency

Immutable Classes

Implementing Immutable Classes

Use the Java API for parallel algorithms

Parallel Streams

Parallel Arrays

jshell

void time(Runnable task) {
    long start = System.nanoTime();
    task.run();
    long end = System.nanoTime();
    System.out.println((end - start) * 1E-9 + " seconds");
}
int SIZE = 100_000_000;
int[] values = new int[SIZE];
Arrays.parallelSetAll(values, i -> (int) (SIZE * Math.sin(i)));
time(() -> Arrays.parallelSort(values));
Arrays.parallelSetAll(values, i -> (int) (SIZE * Math.sin(i)));
time(() -> Arrays.sort(values));

Use the threadsafe data structures in the Java API

Concurrent Hash Maps

Working with Concurrent Hash Maps

concurrentHashMap

Blocking Queues

blockingQueue

Work with atomic values

Atomic Values

Working with Atomic Values

Working with Accumulators

atomic

Become familiar with low-level locks

Locks

Reentrant Locks

Intrinsic Locks

Synchronized Methods

The Monitor Concept

Conditions

lesson04/locks/QueueDemo.java

Understand the characteristics of Java threads

Threads

Interrupting Threads

The InterruptedException

lesson04/interruption

Thread-Local Variables

lesson04/threadLocal

Miscellaneous Thread Properties

Organize asynchronous computations

Long-Running Tasks in UI Callbacks

SwingWorker

Completable Futures

Working with Completable Futures

Dealing with Errors

Combining Results

completableFutures

Run operating system processes

Executing a Process from a Java Program

Building a Process with the ProcessBuilder Class

The Input, Output, and Error Streams

Running the Process

jshell

import java.io.*;
ProcessBuilder builder = new ProcessBuilder("ls", "-al");
Process p = builder.directory(new File("/home/cay")).start();
InputStream processOut = p.getInputStream();
Scanner in = new Scanner(processOut);
while (in.hasNextLine()) System.out.println(in.nextLine());
p.waitFor()