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/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
5. Введение: Ситуация
Всем нужны масштабируемость, надёжность,
производительность
The Free Lunch Is Over, Herb Sutter, 2005
Многопоточность может возникать из-за
условий задачи
Многопроцессорность/многоядерность везде
Slide 5/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
6. История: Цели
Параллелизация за кулисами
Загрузка процессора полезной работой
Хорошие алгоритмы
Slide 6/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
8. История: Состав
Java Concurrency Utilities
Executors
Synchronizers Collections
Atomics Locks Nano time
Slide 8/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
10. История: Атомарные переменные
@since 1.5
Обёртки примитивов, ссылок, управление
полями
– Compare-And-Set
– Атомарная арифметика
Slide 10/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
11. История: Синхронизация
@since 1.5
Semaphores, mutexes, barriers, latches,
exchangers
– Удобство синхронизации
Locks
– Производительность
– Модель памяти. Эффект эквивалентен
synchronized
– Гибкость
Slide 11/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
12. История: Concurrent Collections
@since 1.5
ArrayBlockingQueue, PriorityBlockingQueue,
LinkedBlockingQueue, SynchronousQueue,
DelayQueue
ConcurrentHashMap
CopyOnWriteArrayList
CopyOnWriteArraySet
Slide 12/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
13. История: Concurrent Collections
@since 1.6, @since 1.7
LinkedBlockingDeque, LinkedTransferQueue
ConcurrentSkipListMap
ConcurrentSkipListSet
Slide 13/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
14. История: Task Scheduling
@since 1.5, @since 1.7
Executor’ы
– Выполнение асинхронных задач
– Политики выполнения
Slide 14/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
15. Что нового
Slide 15/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
16. Что нового: JC Utilities
Executors
ForkJoinPool (updated, CountedCompleter)
Collections Accumulators
ConcurrentHashMap (v8) LongAccumulator DoubleAccumulator
LongAdder DoubleAdder
LongAdderTable
Locks Atomics Synchronizers
StampedLock AtomicDoubleArray CompletableFuture
AtomicDouble
Slide 16/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
18. Atomics: Чего не хватает
Для каких примитивных типов нет
Atomic-типов?
В каких числах чаще всего считаем?
Возникают массивы атомарных данных
Slide 18/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
20. Atomics: AtomicDoubleArray
@since 1.8
Брат-близнец AtomicLongArray
Serializable
compareAndSet(int i, double exp, double upd)
addAndGet(int i, double delta)
Равенство битов значений
– doubleToRawLongBits()
Slide 20/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
21. Atomics: Performance
Приводимые результаты
– Intel R○ Xeon R○ E5-2680 (2x8x2, 2.7 GHz)
– Linux x64 (RHEL 5.5, kernel 2.6.32)
– JDK 7 (1.7.0_11)
– OpenJDK JMH 1.0
Slide 21/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
22. Atomics: AtomicDoubleArray
Тест производительности
– Размер массива 2, 621, 440
– Читатели делают get()
– Писатели делают compareAndSet()
– Произвольный равномерный доступ
Slide 22/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
23. Atomics: 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 23/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
25. Locks: Чего бы хотелось
Блокировка на чтение, на запись
Чтение без блокировки
Upgrade/downgrade (RL↔WL)
Простота использования
И чтобы быстро работало
Slide 25/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
26. Locks: ReentrantReadWriteLock
@since 1.5
Lock, блокировка на чтение, на запись
Повторная входимость (reentrancy)
Пробная блокировка, таймауты,
прерываемость
Slide 26/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
27. Locks: ReentrantReadWriteLock
@since 1.5
Lock, блокировка на чтение, на запись
Повторная входимость (reentrancy)
Пробная блокировка, таймауты,
прерываемость
Conditions
Fair/unfair
Serializable. . .
Memory effects
Slide 26/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
28. Locks: ReentrantReadWriteLock
readLock() на чтение, writeLock() на
запись
Попробуйте написать оптимистичное чтение,
гарантировать memory effects
Downgrade WL→RL: захват RL под WL
Внутри работает с ThreadLocal
Slide 27/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
30. Locks: StampedLock
Point
class Point {
private double x, y;
private final StampedLock sl = new StampedLock ();
...
Slide 29/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
32. Locks: StampedLock
Upgrade
void moveIfAtOrigin (double newX , double newY) { // upgrade
long stamp = sl.readLock (); // Could start with optimistic
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 31/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
33. Locks: StampedLock
Оптимистичное чтение
Если проверки неудачные, можно захватить
блокировку
– Обычно удачные
Slide 32/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
34. Locks: StampedLock
Оптимистичное чтение
Если проверки неудачные, можно захватить
блокировку
– Обычно удачные
Выигрыш
– Мало записей ⇒ в разы
– Нет записей ⇒ на порядки
– Вне блокировки проверенное состояние может
стать неактуальным
Slide 32/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
35. Locks: StampedLock
Повышение уровня блокировки
– Может не быть выигрыша, если не
ограничивать запись
– Валидное состояние
Slide 33/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
36. Locks: StampedLock
Повышение уровня блокировки
– Может не быть выигрыша, если не
ограничивать запись
– Валидное состояние
В штатном варианте может быть в разы
быстрее RRWL
– Не гарантировано!
– При этом потребляет меньше ресурсов
– Можно передавать метку
Slide 33/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
38. Accumulators: Задача
Инкрементируем счётчик в разных нитях
Нити подбирают работу и имеют доступ к
общему контексту
void call () { // N threads
...
invocations.increment ();
}
...
long getCount () {
return invocations .get ();
}
Что использовать для invocations?
Slide 35/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
39. Accumulators: Простое решение
AtomicLong invocations = new AtomicLong (0L); // context
...
void call () { // N threads
...
invocations. getAndIncrement ();
}
...
long getCount () { // cumulative value
return invocations .get ();
}
Slide 36/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
41. Accumulators: LongAdder
Защита от коллизий за счёт структуры и
алгоритма
– PaddedAtomicLong[runtime.availableProcessors()]
Простой API
Number
Slide 38/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
42. Accumulators: Решение
LongAdder invocations = new LongAdder (); // context
...
void call () { // N threads
...
invocations.increment ();
}
...
long getCount () { // cumulative value
return invocations .sum ();
}
Slide 39/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
44. 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 41/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
45. Accumulators: Произвольные
коммутативные операции
LongAccumulator
LongAccumulator invocations =
new LongAccumulator (Long ::sum , 0L); // context
...
void call () { // N threads
...
invocations.accumulate (1);
}
...
long getCount () { // cumulative value
return invocations .get ();
}
DoubleAccumulator
Slide 42/57. 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 45/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
49. Accumulators: Подводные камни
Local, ThreadLocal – эффективнее, если
можно применить
get(), reset() под нагрузкой просаживают
производительность
– Обход всех ячеек
Границы эффекта
– Система до насыщения
– Итерации менее 1 мкс
Slide 46/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
51. ConcurrentHashMap: CHMv7
Lock striping
– Concurrency level
– Сегмент - ReentrantLock
get() без блокировки
Защита от алгоритмических атак
– Другой хэш для String
Slide 48/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
52. ConcurrentHashMap: CHMv8
Lock striping
– Concurrency level не используется, подстройка
структуры в процессе работы
– Node (bucket): synchronized или StampedLock
Slide 49/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
53. ConcurrentHashMap: CHMv8
Lock striping
– Concurrency level не используется, подстройка
структуры в процессе работы
– Node (bucket): synchronized или StampedLock
get() без блокировки или под блокировкой
на чтение
Slide 49/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
54. ConcurrentHashMap: CHMv8
Lock striping
– Concurrency level не используется, подстройка
структуры в процессе работы
– Node (bucket): synchronized или StampedLock
get() без блокировки или под блокировкой
на чтение
Защита от алгоритмических атак
– Сбалансированное дерево для Comparable -
performance
Slide 49/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
55. ConcurrentHashMap: v8 vs v7
Тест производительности
– put()
– Integer-like ключи
– Нормальное распределение
– 2, 621, 440 элементов
– concurrencyLevel == 32 (optimal)
Slide 50/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
56. ConcurrentHashMap:
Масштабируемость
1
10
0 20 40 60
Threads
Throughput,ops/usec(logscale)
Benchmark CHMv8 CHMv7 HashMap+ReentrantLock
Slide 51/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
57. ConcurrentHashMap: Часть JDK 8
Часть методов появилась в других мапах
через default-реализации в Map
– putIfAbsent(), computeIfAbsent() атомарны в CHM
Slide 52/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
58. ConcurrentHashMap: Часть JDK 8
Часть методов появилась в других мапах
через default-реализации в Map
– putIfAbsent(), computeIfAbsent() атомарны в CHM
Добавились новые методы и возможности
– map.merge(key, valueSuffix, String::concat)
– chm.values().parallelStream()
Slide 52/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
59. 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)
– stream.map(theMap::get)
Slide 52/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
60. LongAdderTable: Задача
Регистрировать распределение объектов
– Моделирование
– Профилирование
void call () { // N threads
...
invocations.increment("call");
}
...
long getCount(String name) { // cumulative value
return invocations .sum(name );
}
Slide 53/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
63. Заключение: Книги
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 56/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
64. Заключение: Ресурсы
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 57/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
65. Низкоуровневые API: Мотивация
JMM абстрактна, железо конкретно
Есть полезные трюки
Не используйте низкоуровневые API
напрямую
Slide 57/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
66. Низкоуровневые API: Unsafe
Не часть языка
– Обход JMM
– sun.misc
Unsafe API в Hotspot
– Аккуратный
– Абстрактный
– Достаточный
Не используйте Unsafe напрямую, это unsafe
Slide 57/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
67. Низкоуровневые API: Unsafe
Новая механика
– storeFence()
– loadFence()
– fullFence()
– Использование в реализации Locks
Slide 57/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.
68. Низкоуровневые API: StampedLock
Listing 1: Optimistic Read
/* volatile long state */
...
long stamp = sl. tryOptimisticRead (); /* s = state */
double currentX = x;
double currentY = y;
if (!sl.validate(stamp )) { /* unsafe.loadFence () */
...
stamp = sl.writeLock (); /* CAS(state , next) */
x = newX;
y = newY;
sl.unlock(stamp );
Slide 57/57. Copyright c○ 2013, Oracle and/or its affiliates. All rights reserved.