3. 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.
5. Введение: Ресурсы
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.
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.
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 Concurrency Utilities
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.
14. История: Task Scheduling Framework
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. Что нового: 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.
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.
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
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.
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.
35. 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.
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.
39. Accumulators: Задача
Инкрементируем счётчик в разных нитях
Нити подбирают работу и имеют доступ к общему контексту
Slide 39/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
40. 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.
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.
48. 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.
49. Accumulators: Подводные камни
Local, ThreadLocal – эффективнее, если можно применить
get(), reset() под нагрузкой просаживают
производительность
Обход всех ячеек
Границы эффекта
Система до насыщения
Итерации менее 1 мкс
Slide 49/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
51. ConcurrentHashMap: CHMv7
Lock striping
Concurrency level
Сегмент - ReentrantLock
get() без блокировки
Защита от DoS
Другой хэш для String
Slide 51/60. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
52. 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.
53. ConcurrentHashMap: CHMv8 vs CHMv7
Тест производительности
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 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.
55. 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.
59. Заключение: Книги
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.
60. Заключение: Ресурсы
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.