Core Java. Лекция 11

Java Concurrency (окончание).

Иван Пономарёв, КУРС/МФТИ

Part 3. Thread-safe data structures

hydra2

Non-blocking algorithms

  • Locking (via synchronized or ReentrantLock) solves the issue of coordinating the actions of different threads with a variable.

  • But if many threads compete for the lock (high lock contention), the cost of coordinating the threads becomes significant.

  • The alternative is non-blocking algorithms that use special atomic machine instructions (compare-and-swap).

  • In the Java library, classes of atomic variables and thread-safe collections are available, including those implementing non-blocking algorithms.

Atomics

  • package java.util.concurrent.atomic

    • AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference.

    • AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray.

  • Can be used as "enhanced volatiles", as the result of calling set(…​) is visible to other threads via get(…​)

  • Support atomic operations.

Atomic operations in atomic variable classes

getAndSet(newValue)    compareAndSet(expect, update)

incrementAndGet()      decrementAndGet()

getAndIncrement()      getAndDecrement()

getAndAdd(delta)       addAndGet(delta)

getAndUpdate(updateFunction)
updateAndGet(updateFunction)

getAndAccumulate(x, accumulatorBiFunction)
accumulateAndGet(x, accumulatorBiFunction)

Thread-safe collections

  • In earlier versions of Java, it was possible to "make" a collection thread-safe by wrapping it in Collections.synchronizedXXX(…​). This serialized any access to the internal state of the collection. Because of backward compatibility support, doing this is still possible, but not recommended.

  • The price of such a solution is high lock contention.

  • Version 5 introduces classes specifically designed for thread safety, with fewer locks.

  • Their use is preferred.

CopyOnWriteArrayList и CopyOnWriteArraySet

class CopyOnWriteArrayList<E> implements List<E>
class CopyOnWriteArraySet<E> extends AbstractSet<E>
  • Array-based data structures.

  • Recreate themselves from scratch on each modification.

  • It’s expensive, but all reading iterators are stable.

  • Good when there are multiple read operations per one write operation.

ConcurrentLinkedQueue/Deque

ConcurrentLinkedQueue<E> extends AbstractQueue<E>
                                      implements Queue<E>
ConcurrentLinkedDeque<E> extends AbstractCollection<E>
                                      implements Deque<E>
  • Based on non-blocking algorithm (CAS operations)

  • poll() returns null if the queue is empty

  • Under the hood there are (double) linked lists

ConcurrentLinkedQueue/Deque

Diagram
Diagram

Blocking queues: a means of implementing the producer-consumer pattern

blockingqueue
  • put(e) и take() при необходимости ждут.

  • ArrayBlockingQueue — очередь фиксированной ёмкости.

  • LinkedBlockingQueue — ёмкость можно задать, по умолчанию — Integer.MAX_VALUE.

  • PriorityBlockingQueue — очередь с приоритетами без ограничения ёмкости.

  • SynchronousQueue — очередь нулевой ёмкости. Каждый put(e) ждёт, пока другой тред примет элемент.

ConcurrentHashMap

class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>
  • Replaces HashMap for multithreaded data access.

  • Not blocked when reading and rarely blocked when writing.

  • Does not allow the use of null as a key or value.

  • Useful methods are atomic:

    • putIfAbsent(key, value)

    • remove(key, value)

    • replace(key, oldValue, newValue)

ConcurrentHashMap: Java 7-

Diagram

ConcurrentHashMap: Java 8+

Diagram

ConcurrentSkipListMap

class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentNavigableMap<K,V>
  • Replaces TreeMap for multithreaded access.

  • Does not allow null as a key or a value.

  • Has atomic methods.

ConcurrentSkipListMap: идея

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

ConcurrentSkipListMap

Diagram

Часть 4. Executor Framework и кооперативное прерывание

hydra2

Executor Framework

  • Платформенный тред — дорогой ресурс, поэтому мы хотим:

    • ограничивать количество наших тредов, чтобы не устроить Out of Memory,

    • переиспользовать имеющиеся треды, подавая им новые задачи после завершения старых,

    • но если какой-то тред «вылетел» — автоматически создавать новый.

  • В стандартной библиотеке для этого есть Thread Pools, не надо ничего делать самостоятельно.

  • Никто не использует Thread API напрямую.

Executor Framework

//Abstraction of a computational task returning a result
public interface Callable<V> {
  V call() throws Exception;
}</V>

//Abstraction of the "manager of threads"
public interface ExecutorService {
  <T> Future<T> submit(Callable<T> task);
  /*... there are many other methods, will discuss later...*/
}

Future

//Abstraction of the "in progress" result that you can wait for
//finalization or just cancel
public interface Future<V> {
  V get() throws InterruptedException, ExecutionException;
  V get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException;
  boolean cancel(boolean mayInterruptIfRunning);
  boolean isDone();
  boolean isCancelled();
}

Task, Executor, Future

taskexecfuture

Как создать ExecutorService?

public class  Executors {
  //фиксированный размер пула
  public static ExecutorService newFixedThreadPool(int nThreads)
  public static ExecutorService newSingleThreadExecutor()
  //пул растёт по необходимости, держит неактивный тред 60 секунд
  public static ExecutorService newCachedThreadPool()
  //позволяет выполнять задачи с задержкой или периодичностью
  public static
    ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  //запускает виртуальный поток под каждую из задач
  //(что такое виртуальный поток -- скоро объясним!)
  public static ExecutorService newVirtualThreadPerTaskExecutor()
  ...
}

Processing tasks in batches

//Run and wait for everything to finish
//List<Future<T>>, not List<T>, because exceptions are possible
<T>List <Future <T>> invokeAll(
    Collection <? extends Callable <T>> tasks)
        throws InterruptedException

//Run, return the first successful result
//cancel the rest
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

Cancellation of tasks and "termination of service"

//cancel a task if it has not already started
future.cancel(false)
//request task interruption (details ahead)
future.cancel(true)

//Prevent new tasks from being accepted
executorService.shutdown();
//Wait until the accepted tasks are completed
if (!service.awaitTermination(10, TimeUnit.SECONDS)){
    Abort tasks
    service.shutdownNow();
}

Interruption of tasks

  • In early versions of Java, there were (now deprecated) methods for forcibly stopping and suspending/resuming threads, but this turned out to be a bad idea:

    • there is no guarantee that the thread will not stop in the middle of the atomic operation.

    • suspension may leave the lock acquired for an indefinite amount of time

  • All this now is deprecated in favor of cooperative interruption mechanism.

Interrupting threads

  • ExecutorService.shutdownNow() calls the Thread.interrupt() method on threads.

  • the Thread.isInterrupted() method returns the interrupt status of the thread.

  • JMM Interruption Rule: An external thread call to the interrupt() method happens before the interrupted thread knows that it has been interrupted.

Cooperative termination mechanism

  • If the calculations are in a loop, the thread is obliged to periodically check the status of Thread.currentThread().isInterrupted() and, if the flag is set, write to the log the fact of interruption and exit the method.

  • InterruptedException may be thrown on waiting methods. What should we do with it?

What should we do with InterruptedException

  • If circumstances allow, it is best to declare it in throws and not to handle it at all.

  • If we cannot change the method’s signature (e. g. we are implementing run method of Runnable interface which doesn’t throw checked exceptions) then:

} catch (InterruptedException e) {
    //record the fact of interruption to the log...
    ...
    //restore the interrupted status
    Thread.currentThread().interrupt();
    //exit the interrupted method
    return;
}
  • You should never silently "swallow" an InterruptedException !

  • It is recommended to log the fact of interruption to facilitate debugging.

Часть 5. Виртуальные треды

hydra2

Платформенный тред — дорогой ресурс

  • По умолчанию, 1 Мб для стека (определяется параметром JVM -Xss).

  • Один тред ОС: создание может завершиться ошибкой со стороны ОС, даже если в Java heap ещё достаточно места.

  • Создание треда ОС стоит времени.

  • И при этом, многие из них находятся в состоянии waiting!

Java 21, Project Loom: два вида java.lang.Thread

Платформенный тред

Виртуальный тред

Thread
  .currentThread()
  .isVirtual()

false

true

Кто планирует выполнение?

ОС планирует связанный с ним тред ОС.

JVM выбирает платформенный тред (carrier) для выполнения.

На время жизни

Занимает один тред ОС.

Может выполняться на разных платформенных тредах по очереди.

Ожидание на 20K платформенных тредах

5,2 секунды, 20004 стартовавших тредов, 9338 на пике:

List<Thread> threads = new ArrayList<>(20_000);

for (int i = 0; i < 20_000; i++) {
  Thread t = new Thread(() -> {
    try {
      Thread.sleep(1_000);  // simulates blocking I/O
    } catch (InterruptedException ignored) {}
  });
  threads.add(t);
}
threads.forEach(Thread::start);
for (Thread t : threads) t.join(); // wait for all

Ожидание на 20K виртуальных тредах

1,5 секунды, 17 стартовавших тредов, 12 на пикеы:

List<Thread> threads = new ArrayList<>(20_000);

for (int i = 0; i < 20_000; i++) {
  Thread t = Thread.startVirtualThread(() -> { // JDK 21+
    try {
      Thread.sleep(1_000);
    } catch (InterruptedException ignored) {}
  });
  threads.add(t);
}
for (Thread t : threads) t.join();

А что с synchronized?

synchronized (lock) {
    return readFromSocket();
}
  • JDK 21–23. Если чтение приводит к ожиданию, виртуальный тред удерживает carrier (pinning).

  • JDK 24+ В HotSpot виртуальный тред может освободить carrier, даже удерживая монитор (JEP 491).

Часть 6. CompletableFuture

hydra2

CompletableFuture

  • Появились в Java 8, расширяют Future.

  • Позволяют явно задать результат (отсюда 'Completable') и собрать граф асинхронных вычислений.

  • Могут быть использованы так:

CompletableFuture<Integer> f = new CompletableFuture<>();
executor.execute(() -> {
  int n = workHard(arg);
  f.complete(n); });

executor.execute(() -> {
  int n = workSmart(arg);
  f.complete(n); });

executor.execute(() -> {
  Throwable t = ...;
  f.completeExceptionally(t); });

Композиция CompletableFuture с действием

Method

Parameter

Description

thenApply

T→U

Apply a function to the result.

thenAccept

T→void

Like thenApply, but with void result.

thenCompose

T→CompletableFuture<U>

Invoke the function on the result and execute the returned future.

handle

(T, Throwable) → U

Process the result or error and yield a new result.

whenComplete

(T, Throwable) → void

Like handle, but with void result.

Композиция CompletableFuture с действием

Method

Parameter

Description

completeOnTimeout

T, long, TimeUnit

Yield the given value as the result in case of timeout (Java 9+)

orTimeout

long, TimeUnit

Throw `TimeoutException ` in case of timeout (Java 9+)

thenRun

Runnable

Execute the Runnable with void result.

Композиция нескольких CompletableFuture

Method

Parameter

Description

thenCombine

ComletableFuture<U>,
(T, U)→V

Execute both and combine the results with the given function.

thenAcceptBoth

ComletableFuture<U>,
(T, U)→void

Like thenCombine, but with void result.

runAfterBoth

CompletableFuture<?>,
Runnable

Execute the runnable after both complete.

Композиция нескольких CompletableFuture

Method

Parameter

Description

applyToEither

CompletableFuture<T>,
T→V

When a result is available from one or the other, pass it to the given function.

acceptEither

CompletableFuture<T>,
T→void

Like applyToEither, but with void result.

runAfterEither

CompletableFuture<?>,
Runnable

Execute the runnable after one or the other completes.

static allOf

CompletableFuture<?>…​

Complete with void result after all given futures complete.

static anyOf

CompletableFuture<?>…​

Complete after any of the given futures completes, with the same result cast to Object.

If that didn’t seem enough…​

  • Each of these methods has a variant with the postfix Async (for example, thenApplyAsync) that allows you to perform an additional action in another thread of the specified Executor.

Финал! Мы только прошлись по основам

jcip
  • Brian Goetz et al., Java Concurrency in Practice.

  • Released in 2006, in the era of Java 5.0.

  • No new editions were published.

  • It was released in Russian language in 2020!

  • Still the most comprehensive guide to different aspects of multithreaded Java programming.

Code Review Checklist

Синглетон: подход №1

public class Singleton {
  //Создание Singleton "спрятано"
  private static final Singleton instance = new Singleton();

  public static Singleton getInstance() {
    return instance;
  }

  //Лишаем возможности создать экземпляр объекта "извне"
  private Singleton(){
  }
}

"Тяжёлый" объект создаётся всегда, даже если getInstance не будет вызван?

Подход №2

public class Singleton {
    private static Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
           instance = new Singleton();
        }
        return instance;
    }
    private Singleton(){
    }
}

Что с многопоточным доступом к переменной instance?

Подход №3 ?!

public class Singleton {
    private static volatile Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    private Singleton(){
    }
}

Теперь нет гарантии, что экземпляр создаётся только один раз!

Подход №4 ?! ?!

public class Singleton {
    private static Singleton instance;

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    private Singleton(){
    }
}

Все потоки будут выстраиваться в очередь, только чтобы получить доступ к переменной instance?

Подход №5 ?! ?! ?!

public class Singleton {
    private static Singleton instance;
    private static final Object lock = new Object();
    public static Singleton getInstance() {
        if (instance == null)
            synchronized (lock) {
                if (instance == null)
                    instance = new Singleton();
            }
        return instance;
    }
    private Singleton() {
    }
}

Программа сломана. Из-за того, что в первом if-е чтение поля instance не синхронизировано, возможно чтение частично инициализированного объекта (если конструктор Singleton заинлайнен).

Подход №6 . . .

public class Singleton {
    private static volatile Singleton instance;
    private static final Object lock = new Object();
    public static Singleton getInstance() {
        if (instance == null)
            synchronized (lock) {
                if (instance == null)
                    instance = new Singleton();
            }
        return instance;
    }
    private Singleton() {
    }
}

Ну, почти. Только у нас оверхед, потому что два раза читаем volatile-переменную.

Подход №7. Код из книги "Effective Java, 3rd edition"

Joshua Bloch: "On my machine, this method is about 1.4 times as fast as the obvious version without a local variable". [EJ, 3rd ed., pp. 334-335]

public class Singleton {
  private static volatile Singleton instance;
  private static final Object lock = new Object();
  public static Singleton getInstance() {
    Singleton result = instance;
    if (result == null) {
      synchronized (lock) {
        if (instance == null)
          instance = result = new Singleton();
        }
     }
     return result;
  }}

Подход №7. Код из книги "Effective Java, 3rd edition"

Вы уже видите баг в этом коде?
 

public class Singleton {
  private static volatile Singleton instance;
  private static final Object lock = new Object();
  public static Singleton getInstance() {
    Singleton result = instance;
    if (result == null) {
      synchronized (lock) {
        if (instance == null)
          instance = result = new Singleton();
        }
     }
     return result;
  }}

Если при входе в synchronized-блок instance != null, на выходе — null.

Единственно Верный Ленивый Потокобезопасный Синглетон

public class Singleton {
    private static volatile Singleton instance;
    private static final Object lock = new Object();
    public static Singleton getInstance() {
        Singleton result = instance;
        if (result != null)
            return result;

        synchronized (lock) {
            if (instance == null)
                instance = new Singleton();
            return instance;
        }
    }
    private Singleton() {}
}

Или нет?

Подход №8

// Correct lazy initialization in Java
public class Singleton {
    private static class SingletonHolder {
       public static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
    private Singleton() {
    }
}