Обзор нововведений в j.u.c
(JSR 166e)
Дмитрий Чуйко
dmitry.chuyko@oracle.com
Outline
Введение
Что нового
Атомарные переменные
Locks
Accumulators
Collections
Slide 2/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
The following is intended to outline our general product direction. It
is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in
making purchasing decisions. The development, release, and timing
of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Slide 3/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Введение
Slide 4/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Введение: Ресурсы
Concurrency JSR-166 Interest Site
http://g.oswego.edu/dl/concurrency-interest/
JDK 8
http://jdk8.java.net/
Project Lambda
http://openjdk.java.net/projects/lambda/
JMH
http://openjdk.java.net/projects/code-tools/jmh/
Slide 5/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Введение: Мир, в котором мы живём
Всем нужны масштабируемость, надёжность,
производительность
The Free Lunch Is Over Herb Sutter
Многопоточность может возникать из-за условий задачи
Многопроцессорность/многоядерность везде
Slide 6/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Цели
Параллелизация за кулисами
Загрузка процессора полезной работой
Хорошие алгоритмы
Slide 7/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Java Concurrency Timeline
JDK 1.0
  JMM
  synchronizied
  Thread
1996 1997 2004
JDK 1.2
  Collections
JDK 5
  JMM
  java.util.concurrent
JSRs
  JSR 133
  JSR 166
Doug Lea
 Concurrency
package
1998 2006
JDK 6
  Navigable
JSRs
  JSR 166x
2011
JDK 7
  FJP,
JSRs
  JSR 166y
JDK 8
  java.util.concurrent
JSRs
  JSR 166e
Slide 8/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Алгоритмы с координацией
Блокирующиеся (blocking)
Неблокирующиеся (nonblocking) При остановке одной
нити у других есть шанс закончить работу
Без препятствий (obstruction-free) Любая нить в изоляции
может закончить работу
Свободные от блокировок (lock-free) На каждом шаге
продвигается какая-либо из нитей
Без ожиданий (wait-free) Каждая нить продвигается
Алгоритмы, основанные на CAS, могут быть nonblocking
lock-free
Slide 9/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Состав
Java Concurrency Utilities
Executors
Synchronizers Collections
Atomics Locks Nano time
Slide 10/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Атомарные переменные
Обёртки примитивов, ссылок, управление полями
Compare-And-Set
Атомарная арифметика
Slide 11/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Синхронизация
Semaphores, mutexes, barriers, latches, exchangers
Удобство синхронизации
Locks
Производительность
Модель памяти. Эффект эквивалентен synchronized
Гибкость
Slide 12/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Concurrent Collections
(Blocking)(De)Queue, Map, List
Параллельный доступ
Высокая производительность
Slide 13/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
История: Task Scheduling Framework
Executor’ы
Выполнение асинхронных задач
Политики выполнения
Slide 14/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Что нового
Slide 15/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Что нового: Тот же фундамент
Runtime
LockSupport
Unsafe
JVM
Intrinsics
OS
pthreads mutex
Hardware
CAS
Slide 16/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Что нового: JC Utilities
Executors
CompletableFuture CountedCompleter ForkJoinPool
Collections Accumulators Combined
ConcurrentHashMap LongAccumulator LongAdderTable
DoubleAccumulator
LongAdder
DoubleAdder
Locks Atomics
StampedLock AtomicDoubleArray
AtomicDouble
Slide 17/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Низкоуровневые API: Мотивация
JMM абстрактна, железо конкретно
Есть полезные трюки
Не используйте низкоуровневые API напрямую
Slide 18/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Низкоуровневые API: Unsafe
Не часть языка
Обход JMM
sun.misc
Unsafe API в Hotspot
Аккуратный
Абстрактный
Достаточный
Не используйте Unsafe напрямую, это unsafe
Slide 19/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Низкоуровневые API: Unsafe
Новая механика
storeFence()
loadFence()
fullFence()
Использование в реализации Locks
Slide 20/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные
Slide 21/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: Чего не хватает
Для каких примитивных типов нет Atomic-типов?
В каких числах чаще всего считаем?
Возникают массивы атомарных данных
Slide 22/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: AtomicDouble
Брат-близнец AtomicLong
Number, Serializable
compareAndSet(double expect, double update)
addAndGet(double delta)
Равенство битов значений
doubleToRawLongBits()
Slide 23/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: AtomicDoubleArray
Брат-близнец AtomicLongArray
Serializable
compareAndSet(int i, double expect, double update)
addAndGet(int i, double delta)
Равенство битов значений
doubleToRawLongBits()
Slide 24/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: Performance
Приводимые результаты
Intel R○ Xeon R○ E5-2680 (2x8x2)
Linux
JDK 7
OpenJDK JMH 1.0
Slide 25/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: AtomicDoubleArray
Тест производительности
Не слишком маленький массив
Читатели делают get()
Писатели делают compareAndSet()
Произвольный равномерный доступ
Slide 26/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Атомарные переменные: AtomicDoubleArray
0
200
400
25 50 75
% of writers
Readthroughput,ops/usec
Benchmark
AtomicDouble[]
AtomicDoubleArray
T=32
0
100
200
300
25 50 75 100
% of writers
Writethroughput,ops/usec
Benchmark
AtomicDouble[]
AtomicDoubleArray
T=32
Slide 27/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks
Slide 28/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: ReentrantReadWriteLock
Lock, блокировка на чтение, на запись
Повторная входимость (reentrancy)
Пробная блокировка, таймауты, прерываемость
Conditions
Fair/unfair
Serializable. . .
Memory effects
Slide 29/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: Чего бы хотелось
Блокировка на чтение, на запись
Оптимистичные блокировки
Upgrade/downgrade
Простота использования
И чтобы быстро работало
Slide 30/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: ReentrantReadWriteLock
readLock() на чтение, writeLock() на запись
Попробуйте написать оптимистичную блокировку,
гарантировать memory effects
Downgrade: захват RL под WL
Постоянно работает с ThreadLocal
Slide 31/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock
Пример из javadoc
Slide 32/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock
Listing 1: Point
class Point {
private double x, y;
private final StampedLock sl = new StampedLock ();
...
Slide 33/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock
Listing 2: Optimistic Read
double distanceFromOrigin () { // A read -only method
long stamp = sl. tryOptimisticRead ();
double currentX = x, currentY = y;
if (!sl.validate(stamp )) {
stamp = sl.readLock ();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp );
}
}
return Math.sqrt(currentX * currentX + currentY * currentY );
}
Slide 34/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock. Upgrade
void moveIfAtOrigin (double newX , double newY) { // upgrade
// Could instead start with optimistic , not read mode
long stamp = sl.readLock ();
try {
while (x == 0.0 && y == 0.0) {
long ws = sl. tryConvertToWriteLock (stamp );
if (ws != 0L) {
stamp = ws;
x = newX;
y = newY;
break;
}
else {
sl.unlockRead(stamp );
stamp = sl.writeLock ();
}
}
} finally {
sl.unlock(stamp );
}
}
Slide 35/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock
Оптимистичные блокировки
Если проверки неудачные, можно захватить блокировку
Обычно удачные
Выигрыш
Мало записей => в разы
Нет записей => на порядки
Вне блокировки, проверенное состояние может стать
неактуальным
Slide 36/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Locks: StampedLock
Повышение уровня блокировки
Может не быть выигрыша, если не ограничивать запись
Валидное состояние
В обычном варианте может быть в разы быстрее RRWL
Не гарантировано!
При этом потребляет меньше ресурсов
Можно передавать метку
Slide 37/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators
Slide 38/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Задача
Инкрементируем счётчик в разных нитях
Нити подбирают работу и имеют доступ к общему контексту
Slide 39/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Простое решение
AtomicLong atomicLong = new AtomicLong (0L); // context
...
atomicLong. getAndIncrement (); // N threads
...
long sharedSum = atomicLong.get ();
Slide 40/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: AtomicLong
Sharing
Spin loop + CAS, много
Slide 41/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: LongAdder
Защита от коллизий за счёт структуры и алгоритма
Похож на комбинацию unshared padded AtomicLong’ов
Простой API
Number
Slide 42/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Решение
LongAdder longAdder = new LongAdder (); // context
...
longAdder.increment (); // N threads
...
long sharedSum = longAdder.sum ();
Slide 43/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: DoubleAdder
Аналогичен LongAdder, только для double
Большая часть логики одинаковая, базовый класс Striped64
Slide 44/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Atomic Update
// AtomicLong , JDK 7
public final long addAndGet(long delta) {
for (;;) {
long current = get ();
long next = current + delta;
if ( compareAndSet (current , next ))
return next;
}
}
Slide 45/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Произвольные коммутативные
операции
Заменяем ’+’ функцией
Striped64, Number
LongAccumulator аналогичен LongAdder
new LongAccumulator(Long::sum, 0L)
DoubleAccumulator аналогичен DoubleAdder
new DoubleAccumulator(Double::sum, 0.0D)
Slide 46/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: LongMaxUpdater
new LongAccumulator(Long::max, Long.MIN_VALUE)
Тест производительности
accumulate(nextLocalLongMax)
Slide 47/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: LongMaxUpdater
10
100
1000
0 20 40 60
Threads
Throughput,ops/usec(logscale)
Benchmark Unshared CAS LongMaxUpdater AtomicLong long+Lock
Slide 48/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Accumulators: Подводные камни
Local, ThreadLocal – эффективнее, если можно применить
get(), reset() под нагрузкой просаживают
производительность
Обход всех ячеек
Границы эффекта
Система до насыщения
Итерации менее 1 мкс
Slide 49/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Collections
Slide 50/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
ConcurrentHashMap: CHMv7
Lock striping
Concurrency level
Сегмент - ReentrantLock
get() без блокировки
Защита от DoS
Другой хэш для String
Slide 51/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
ConcurrentHashMap: CHMv8
Lock striping
Concurrency level не используется, подстройка в процессе работы
Node: synchronized или AbstractQueuedSynchronizer
get() без блокировки или под блокировкой на чтение
Защита от DoS
Сбалансированное дерево для Comparable - performance
Slide 52/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
ConcurrentHashMap: CHMv8 vs CHMv7
Тест производительности
Integer-like ключи
concurrencyLevel == 32
Размер порядка L3
Нормальное распределение
put()
Slide 53/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
ConcurrentHashMap: Масштабируемость
1
10
0 20 40 60
Threads
Throughput,ops/usec(logscale)
Benchmark CHMv8 CHMv7 HashMap+ReentrantLock
Slide 54/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
ConcurrentHashMap: Часть JDK 8
Часть методов появилась в других мапах через
default-реализации в Map
putIfAbsent(), computeIfAbsent() атомарны в CHM
Добавились новые методы и возможности
map.merge(key, valueSuffix, String::concat)
chm.values().parallelStream()
Можно использовать лямбды и method reference
int2IntMap.computeIfAbsent(100, (k)->k/3)
theMap::get можно использовать для... map()
Slide 55/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
LongAdderTable: Задача
Регистрировать распределение объектов
Моделирование
Профилирование
Slide 56/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
LongAdderTable: Решение
Естественное использование LongAdder
ConcurrentHashMap<K, LongAdder>
Serializable
Slide 57/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
LongAdderTable: API
install(K key)
increment(K key)
add(K key)
sum(K key)
и другие
Slide 58/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Заключение: Книги
Java Concurrency in Practice
Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David
Holmes, Doug Lea
Concurrent Programming in Java: Design Principles and
Patterns
Doug Lea
Slide 59/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
Заключение: Ресурсы
Concurrency JSR-166 Interest Site
http://g.oswego.edu/dl/concurrency-interest/
JDK 8
http://jdk8.java.net/
Project Lambda
http://openjdk.java.net/projects/lambda/
JMH
http://openjdk.java.net/projects/code-tools/jmh/
Slide 60/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.

What's new in java.util.concurrent

  • 1.
    Обзор нововведений вj.u.c (JSR 166e) Дмитрий Чуйко dmitry.chuyko@oracle.com
  • 2.
  • 3.
    The following isintended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Slide 3/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 4.
    Введение Slide 4/60. Copyrightc○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 5.
    Введение: Ресурсы Concurrency JSR-166Interest Site http://g.oswego.edu/dl/concurrency-interest/ JDK 8 http://jdk8.java.net/ Project Lambda http://openjdk.java.net/projects/lambda/ JMH http://openjdk.java.net/projects/code-tools/jmh/ Slide 5/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 6.
    Введение: Мир, вкотором мы живём Всем нужны масштабируемость, надёжность, производительность The Free Lunch Is Over Herb Sutter Многопоточность может возникать из-за условий задачи Многопроцессорность/многоядерность везде Slide 6/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 7.
    История: Цели Параллелизация закулисами Загрузка процессора полезной работой Хорошие алгоритмы Slide 7/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 8.
    История: Java ConcurrencyTimeline JDK 1.0   JMM   synchronizied   Thread 1996 1997 2004 JDK 1.2   Collections JDK 5   JMM   java.util.concurrent JSRs   JSR 133   JSR 166 Doug Lea  Concurrency package 1998 2006 JDK 6   Navigable JSRs   JSR 166x 2011 JDK 7   FJP, JSRs   JSR 166y JDK 8   java.util.concurrent JSRs   JSR 166e Slide 8/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 9.
    История: Алгоритмы скоординацией Блокирующиеся (blocking) Неблокирующиеся (nonblocking) При остановке одной нити у других есть шанс закончить работу Без препятствий (obstruction-free) Любая нить в изоляции может закончить работу Свободные от блокировок (lock-free) На каждом шаге продвигается какая-либо из нитей Без ожиданий (wait-free) Каждая нить продвигается Алгоритмы, основанные на CAS, могут быть nonblocking lock-free Slide 9/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 10.
    История: Состав Java ConcurrencyUtilities Executors Synchronizers Collections Atomics Locks Nano time Slide 10/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 11.
    История: Атомарные переменные Обёрткипримитивов, ссылок, управление полями Compare-And-Set Атомарная арифметика Slide 11/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 12.
    История: Синхронизация Semaphores, mutexes,barriers, latches, exchangers Удобство синхронизации Locks Производительность Модель памяти. Эффект эквивалентен synchronized Гибкость Slide 12/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 13.
    История: Concurrent Collections (Blocking)(De)Queue,Map, List Параллельный доступ Высокая производительность Slide 13/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 14.
    История: Task SchedulingFramework Executor’ы Выполнение асинхронных задач Политики выполнения Slide 14/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 15.
    Что нового Slide 15/60.Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 16.
    Что нового: Тотже фундамент Runtime LockSupport Unsafe JVM Intrinsics OS pthreads mutex Hardware CAS Slide 16/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 17.
    Что нового: JCUtilities Executors CompletableFuture CountedCompleter ForkJoinPool Collections Accumulators Combined ConcurrentHashMap LongAccumulator LongAdderTable DoubleAccumulator LongAdder DoubleAdder Locks Atomics StampedLock AtomicDoubleArray AtomicDouble Slide 17/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 18.
    Низкоуровневые API: Мотивация JMMабстрактна, железо конкретно Есть полезные трюки Не используйте низкоуровневые API напрямую Slide 18/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 19.
    Низкоуровневые API: Unsafe Нечасть языка Обход JMM sun.misc Unsafe API в Hotspot Аккуратный Абстрактный Достаточный Не используйте Unsafe напрямую, это unsafe Slide 19/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 20.
    Низкоуровневые API: Unsafe Новаямеханика storeFence() loadFence() fullFence() Использование в реализации Locks Slide 20/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 21.
    Атомарные переменные Slide 21/60.Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 22.
    Атомарные переменные: Чегоне хватает Для каких примитивных типов нет Atomic-типов? В каких числах чаще всего считаем? Возникают массивы атомарных данных Slide 22/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 23.
    Атомарные переменные: AtomicDouble Брат-близнецAtomicLong Number, Serializable compareAndSet(double expect, double update) addAndGet(double delta) Равенство битов значений doubleToRawLongBits() Slide 23/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 24.
    Атомарные переменные: AtomicDoubleArray Брат-близнецAtomicLongArray Serializable compareAndSet(int i, double expect, double update) addAndGet(int i, double delta) Равенство битов значений doubleToRawLongBits() Slide 24/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 25.
    Атомарные переменные: Performance Приводимыерезультаты Intel R○ Xeon R○ E5-2680 (2x8x2) Linux JDK 7 OpenJDK JMH 1.0 Slide 25/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 26.
    Атомарные переменные: AtomicDoubleArray Тестпроизводительности Не слишком маленький массив Читатели делают get() Писатели делают compareAndSet() Произвольный равномерный доступ Slide 26/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 27.
    Атомарные переменные: AtomicDoubleArray 0 200 400 2550 75 % of writers Readthroughput,ops/usec Benchmark AtomicDouble[] AtomicDoubleArray T=32 0 100 200 300 25 50 75 100 % of writers Writethroughput,ops/usec Benchmark AtomicDouble[] AtomicDoubleArray T=32 Slide 27/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 28.
    Locks Slide 28/60. Copyrightc○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 29.
    Locks: ReentrantReadWriteLock Lock, блокировкана чтение, на запись Повторная входимость (reentrancy) Пробная блокировка, таймауты, прерываемость Conditions Fair/unfair Serializable. . . Memory effects Slide 29/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 30.
    Locks: Чего быхотелось Блокировка на чтение, на запись Оптимистичные блокировки Upgrade/downgrade Простота использования И чтобы быстро работало Slide 30/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 31.
    Locks: ReentrantReadWriteLock readLock() начтение, writeLock() на запись Попробуйте написать оптимистичную блокировку, гарантировать memory effects Downgrade: захват RL под WL Постоянно работает с ThreadLocal Slide 31/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 32.
    Locks: StampedLock Пример изjavadoc Slide 32/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 33.
    Locks: StampedLock Listing 1:Point class Point { private double x, y; private final StampedLock sl = new StampedLock (); ... Slide 33/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 34.
    Locks: StampedLock Listing 2:Optimistic Read double distanceFromOrigin () { // A read -only method long stamp = sl. tryOptimisticRead (); double currentX = x, currentY = y; if (!sl.validate(stamp )) { stamp = sl.readLock (); try { currentX = x; currentY = y; } finally { sl.unlockRead(stamp ); } } return Math.sqrt(currentX * currentX + currentY * currentY ); } Slide 34/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 35.
    Locks: StampedLock. Upgrade voidmoveIfAtOrigin (double newX , double newY) { // upgrade // Could instead start with optimistic , not read mode long stamp = sl.readLock (); try { while (x == 0.0 && y == 0.0) { long ws = sl. tryConvertToWriteLock (stamp ); if (ws != 0L) { stamp = ws; x = newX; y = newY; break; } else { sl.unlockRead(stamp ); stamp = sl.writeLock (); } } } finally { sl.unlock(stamp ); } } Slide 35/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 36.
    Locks: StampedLock Оптимистичные блокировки Еслипроверки неудачные, можно захватить блокировку Обычно удачные Выигрыш Мало записей => в разы Нет записей => на порядки Вне блокировки, проверенное состояние может стать неактуальным Slide 36/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 37.
    Locks: StampedLock Повышение уровняблокировки Может не быть выигрыша, если не ограничивать запись Валидное состояние В обычном варианте может быть в разы быстрее RRWL Не гарантировано! При этом потребляет меньше ресурсов Можно передавать метку Slide 37/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 38.
    Accumulators Slide 38/60. Copyrightc○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 39.
    Accumulators: Задача Инкрементируем счётчикв разных нитях Нити подбирают работу и имеют доступ к общему контексту Slide 39/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 40.
    Accumulators: Простое решение AtomicLongatomicLong = new AtomicLong (0L); // context ... atomicLong. getAndIncrement (); // N threads ... long sharedSum = atomicLong.get (); Slide 40/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 41.
    Accumulators: AtomicLong Sharing Spin loop+ CAS, много Slide 41/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 42.
    Accumulators: LongAdder Защита отколлизий за счёт структуры и алгоритма Похож на комбинацию unshared padded AtomicLong’ов Простой API Number Slide 42/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 43.
    Accumulators: Решение LongAdder longAdder= new LongAdder (); // context ... longAdder.increment (); // N threads ... long sharedSum = longAdder.sum (); Slide 43/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 44.
    Accumulators: DoubleAdder Аналогичен LongAdder,только для double Большая часть логики одинаковая, базовый класс Striped64 Slide 44/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 45.
    Accumulators: Atomic Update //AtomicLong , JDK 7 public final long addAndGet(long delta) { for (;;) { long current = get (); long next = current + delta; if ( compareAndSet (current , next )) return next; } } Slide 45/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 46.
    Accumulators: Произвольные коммутативные операции Заменяем’+’ функцией Striped64, Number LongAccumulator аналогичен LongAdder new LongAccumulator(Long::sum, 0L) DoubleAccumulator аналогичен DoubleAdder new DoubleAccumulator(Double::sum, 0.0D) Slide 46/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 47.
    Accumulators: LongMaxUpdater new LongAccumulator(Long::max,Long.MIN_VALUE) Тест производительности accumulate(nextLocalLongMax) Slide 47/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 48.
    Accumulators: LongMaxUpdater 10 100 1000 0 2040 60 Threads Throughput,ops/usec(logscale) Benchmark Unshared CAS LongMaxUpdater AtomicLong long+Lock Slide 48/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 49.
    Accumulators: Подводные камни Local,ThreadLocal – эффективнее, если можно применить get(), reset() под нагрузкой просаживают производительность Обход всех ячеек Границы эффекта Система до насыщения Итерации менее 1 мкс Slide 49/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 50.
    Collections Slide 50/60. Copyrightc○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 51.
    ConcurrentHashMap: CHMv7 Lock striping Concurrencylevel Сегмент - ReentrantLock get() без блокировки Защита от DoS Другой хэш для String Slide 51/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 52.
    ConcurrentHashMap: CHMv8 Lock striping Concurrencylevel не используется, подстройка в процессе работы Node: synchronized или AbstractQueuedSynchronizer get() без блокировки или под блокировкой на чтение Защита от DoS Сбалансированное дерево для Comparable - performance Slide 52/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 53.
    ConcurrentHashMap: CHMv8 vsCHMv7 Тест производительности Integer-like ключи concurrencyLevel == 32 Размер порядка L3 Нормальное распределение put() Slide 53/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 54.
    ConcurrentHashMap: Масштабируемость 1 10 0 2040 60 Threads Throughput,ops/usec(logscale) Benchmark CHMv8 CHMv7 HashMap+ReentrantLock Slide 54/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 55.
    ConcurrentHashMap: Часть JDK8 Часть методов появилась в других мапах через default-реализации в Map putIfAbsent(), computeIfAbsent() атомарны в CHM Добавились новые методы и возможности map.merge(key, valueSuffix, String::concat) chm.values().parallelStream() Можно использовать лямбды и method reference int2IntMap.computeIfAbsent(100, (k)->k/3) theMap::get можно использовать для... map() Slide 55/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 56.
    LongAdderTable: Задача Регистрировать распределениеобъектов Моделирование Профилирование Slide 56/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 57.
    LongAdderTable: Решение Естественное использованиеLongAdder ConcurrentHashMap<K, LongAdder> Serializable Slide 57/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 58.
    LongAdderTable: API install(K key) increment(Kkey) add(K key) sum(K key) и другие Slide 58/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 59.
    Заключение: Книги Java Concurrencyin Practice Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea Concurrent Programming in Java: Design Principles and Patterns Doug Lea Slide 59/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
  • 60.
    Заключение: Ресурсы Concurrency JSR-166Interest Site http://g.oswego.edu/dl/concurrency-interest/ JDK 8 http://jdk8.java.net/ Project Lambda http://openjdk.java.net/projects/lambda/ JMH http://openjdk.java.net/projects/code-tools/jmh/ Slide 60/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.