SlideShare a Scribd company logo
1 of 26
Locks? We don’t need no
       stinkin’ Locks!

            @mikeb2701
http://bad-concurrency.blogspot.com
                                Image: http://subcirlce.co.uk
Memory Models
Happens-Before
Causality
Causality
  Fear will keep the
 local systems inline.
     instructions
           - Grand Moff Wilhuff Tarkin
•   Loads are not reordered with other loads.


•   Stores are not reordered with other stores.


•   Stores are not reordered with older loads.


•   In a multiprocessor system, memory ordering obeys causality (memory
    ordering respects transitive visibility).


•   In a multiprocessor system, stores to the same location have a total order.


•   In a multiprocessor system, locked instructions to the same
    location have a total order.


•   Loads and Stores are not reordered with locked instructions.
Non-Blocking
 Primitives
Unsafe
public class AtomicLong extends Number
                        implements Serializable {

    // ...
    private volatile long value;

    // ...
    /**
      * Sets to the given value.
      *
      * @param newValue the new value
      */
    public final void set(long newValue) {
         value = newValue;
    }

    // ...
}
# {method} 'set' '(J)V' in 'java/util/concurrent/atomic/AtomicLong'
# this:       rsi:rsi   = 'java/util/concurrent/atomic/AtomicLong'
# parm0:      rdx:rdx   = long
#             [sp+0x20] (sp of caller)
  mov    0x8(%rsi),%r10d
  shl    $0x3,%r10
  cmp    %r10,%rax
  jne    0x00007f1f410378a0 ;     {runtime_call}
  xchg   %ax,%ax
  nopl   0x0(%rax,%rax,1)
  xchg   %ax,%ax
  push   %rbp
  sub    $0x10,%rsp
  nop
  mov    %rdx,0x10(%rsi)
  lock addl $0x0,(%rsp)     ;*putfield value
                            ; - j.u.c.a.AtomicLong::set@2 (line 112)
  add    $0x10,%rsp
  pop    %rbp
  test   %eax,0xa40fd06(%rip)         # 0x00007f1f4b471000
                            ;   {poll_return}
public class AtomicLong extends Number
                        implements Serializable {


    // setup to use Unsafe.compareAndSwapLong for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    // ...
    /**
      * Eventually sets to the given value.
      *
      * @param newValue the new value
      * @since 1.6
      */
    public final void lazySet(long newValue) {
         unsafe.putOrderedLong(this, valueOffset, newValue);
    }

    // ...
}
# {method} 'lazySet' '(J)V' in 'java/util/concurrent/atomic/
AtomicLong'
# this:       rsi:rsi   = 'java/util/concurrent/atomic/AtomicLong'
# parm0:      rdx:rdx   = long
#             [sp+0x20] (sp of caller)
  mov    0x8(%rsi),%r10d
  shl    $0x3,%r10
  cmp    %r10,%rax
  jne    0x00007f1f410378a0 ;     {runtime_call}
  xchg   %ax,%ax
  nopl   0x0(%rax,%rax,1)
  xchg   %ax,%ax
  push   %rbp
  sub    $0x10,%rsp
  nop
  mov    %rdx,0x10(%rsi)     ;*invokevirtual putOrderedLong
                             ; - AtomicLong::lazySet@8 (line 122)
  add    $0x10,%rsp
  pop    %rbp
  test   %eax,0xa41204b(%rip)         # 0x00007f1f4b471000
                             ;   {poll_return}
public class AtomicInteger extends Number
                           implements Serializable {

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    private volatile int value;

    //...

    public final boolean compareAndSet(int expect,
                                       int update) {
        return unsafe.compareAndSwapInt(this, valueOffset,
                                        expect, update);
    }
}
# {method} 'compareAndSet' '(JJ)Z' in 'java/util/concurrent/
atomic/AtomicLong'
  # this:       rsi:rsi    = 'java/util/concurrent/atomic/AtomicLong'
  # parm0:      rdx:rdx    = long
  # parm1:      rcx:rcx    = long
  #             [sp+0x20] (sp of caller)
  mov     0x8(%rsi),%r10d
  shl     $0x3,%r10
  cmp     %r10,%rax
  jne     0x00007f6699037a60 ;      {runtime_call}
  xchg    %ax,%ax
  nopl    0x0(%rax,%rax,1)
  xchg    %ax,%ax
  sub     $0x18,%rsp
  mov     %rbp,0x10(%rsp)
  mov     %rdx,%rax
  lock cmpxchg %rcx,0x10(%rsi)
  sete    %r11b
  movzbl %r11b,%r11d ;*invokevirtual compareAndSwapLong
                        ; - j.u.c.a.AtomicLong::compareAndSet@9 (line
149)
  mov     %r11d,%eax
  add     $0x10,%rsp
  pop     %rbp
  test    %eax,0x91df935(%rip)          # 0x00007f66a223e000
                        ;   {poll_return}
set()   compareAndSet      lazySet()
  9



6.75



 4.5



2.25



  0
                 nanoseconds/op
Example - Disruptor Multi-producer




private void publish(Disruptor disruptor, long value) {
    long next = disruptor.next();
    disruptor.setValue(next, value);
    disruptor.publish(next);
}
Example - Disruptor Multi-producer
public long next() {
    long next;
    long current;

    do {
        current = nextSequence.get();
        next = current + 1;
        while (next > (readSequence.get() + size)) {
            LockSupport.parkNanos(1L);
            continue;
        }
    } while (!nextSequence.compareAndSet(current, next));

    return next;
}
Algorithm: Spin - 1



public void publish(long sequence) {
    long sequenceMinusOne = sequence - 1;
    while (cursor.get() != sequenceMinusOne) {
        // Spin
    }

    cursor.lazySet(sequence);
}
Spin - 1
                    25



                  18.75
million ops/sec




                   12.5



                   6.25



                     0
                          1   2   3     4         5      6   7   8
                                      Producer Threads
Algorithm: Co-Op
public void publish(long sequence) {
    int counter = RETRIES;
    while (sequence - cursor.get() > pendingPublication.length()) {
        if (--counter == 0) {
            Thread.yield();
            counter = RETRIES;
        }
    }

    long expectedSequence = sequence - 1;
    pendingPublication.set((int) sequence & pendingMask, sequence);

    if (cursor.get() >= sequence) { return; }

    long nextSequence = sequence;
    while (cursor.compareAndSet(expectedSequence, nextSequence)) {
        expectedSequence = nextSequence;
        nextSequence++;
        if (pendingPublication.get((int) nextSequence & pendingMask) != nextSequence) {
            break;
        }
    }
}
Spin - 1              Co-Op
                   30



                  22.5
million ops/sec




                   15



                   7.5



                    0
                         1   2   3            4         5      6   7   8
                                            Producer Threads
Algorithm: Buffer
public long next() {
    long next;
    long current;

    do {
        current = cursor.get();
        next = current + 1;
        while (next > (readSequence.get() + size)) {
            LockSupport.parkNanos(1L);
            continue;
        }
    } while (!cursor.compareAndSet(current, next));

    return next;
}
Algorithm: Buffer


public void publish(long sequence) {
    int publishedValue = (int) (sequence >>> indexShift);
    published.set(indexOf(sequence), publishedValue);
}



// Get Value
int availableValue = (int) (current >>> indexShift);
int index = indexOf(current);
while (published.get(index) != availableValue) {
     // Spin
}
Spin - 1   Co-Op             Buffer
                   70



                  52.5
million ops/sec




                   35



                  17.5



                    0
                         1   2        3     4             5       6    7   8
                                                Threads
Stuff that sucks...
Q&A
• https://github.com/mikeb01/jax2012
• http://www.lmax.com/careers
• http://www.infoq.com/presentations/Lock-
  free-Algorithms
• http://www.youtube.com/watch?
  v=DCdGlxBbKU4

More Related Content

What's hot

The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
Show innodb status
Show innodb statusShow innodb status
Show innodb statusjustlooks
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210Mahmoud Samir Fayed
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...Security Session
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargentajaxconf
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debuggingJungMinSEO5
 
Don’t block the event loop!
Don’t block the event loop!Don’t block the event loop!
Don’t block the event loop!hujinpu
 
Teorical 1
Teorical 1Teorical 1
Teorical 1everblut
 
W8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorW8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorDaniel Roggen
 
Promises in JavaScript
Promises in JavaScriptPromises in JavaScript
Promises in JavaScriptRevath S Kumar
 
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...PROIDEA
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)Max Klymyshyn
 
Theorical 1
Theorical 1Theorical 1
Theorical 1everblut
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierNodejsFoundation
 

What's hot (20)

The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
Show innodb status
Show innodb statusShow innodb status
Show innodb status
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Crash Fast & Furious
Crash Fast & FuriousCrash Fast & Furious
Crash Fast & Furious
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...
Robots against robots: How a Machine Learning IDS detected a novel Linux Botn...
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 
Don’t block the event loop!
Don’t block the event loop!Don’t block the event loop!
Don’t block the event loop!
 
Teorical 1
Teorical 1Teorical 1
Teorical 1
 
W8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorW8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational Processor
 
Promises in JavaScript
Promises in JavaScriptPromises in JavaScript
Promises in JavaScript
 
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
 
Theorical 1
Theorical 1Theorical 1
Theorical 1
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
 

Viewers also liked

Agenda 6è b setmana 46 -novembre-curs 16-17
Agenda 6è b setmana 46 -novembre-curs 16-17Agenda 6è b setmana 46 -novembre-curs 16-17
Agenda 6è b setmana 46 -novembre-curs 16-176sise
 
4 Ways to Merge IBM i Data with Microsoft Excel
4 Ways to Merge IBM i Data with Microsoft Excel4 Ways to Merge IBM i Data with Microsoft Excel
4 Ways to Merge IBM i Data with Microsoft ExcelHelpSystems
 
Agenda setmana 48 -nov-desembre-curs16-17
Agenda setmana 48 -nov-desembre-curs16-17Agenda setmana 48 -nov-desembre-curs16-17
Agenda setmana 48 -nov-desembre-curs16-176sise
 
Container communication on lattice #2
Container communication on lattice #2Container communication on lattice #2
Container communication on lattice #2Kenta Shinohara
 
Sunset park, paul auster
Sunset park, paul austerSunset park, paul auster
Sunset park, paul austertaniibiris
 
Agenda setmana 51 -desembre-curs16-17
Agenda setmana 51 -desembre-curs16-17Agenda setmana 51 -desembre-curs16-17
Agenda setmana 51 -desembre-curs16-176sise
 
El ordenador y sus componentes.
El ordenador y sus componentes.El ordenador y sus componentes.
El ordenador y sus componentes.taniibiris
 
2do como-se-aprende-a-jugar-al-futbol
2do como-se-aprende-a-jugar-al-futbol2do como-se-aprende-a-jugar-al-futbol
2do como-se-aprende-a-jugar-al-futboldiegocamuss
 
Case histories luigi nespoli slogan
Case histories luigi nespoli sloganCase histories luigi nespoli slogan
Case histories luigi nespoli sloganLuigi Nespoli
 
La Empresa Y Su Entorno
La Empresa Y Su EntornoLa Empresa Y Su Entorno
La Empresa Y Su EntornoRyan Ximenez
 
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...https://www.facebook.com/garmentspace
 
Microsoft excel 2010 intermediated advanced
Microsoft excel 2010 intermediated advancedMicrosoft excel 2010 intermediated advanced
Microsoft excel 2010 intermediated advancedsmittichai chaiyawong
 
Знаете ли вы сказки А.С. Пушкина
Знаете ли вы сказки А.С. ПушкинаЗнаете ли вы сказки А.С. Пушкина
Знаете ли вы сказки А.С. ПушкинаNatalya Dyrda
 
La communication média et hors média
La communication média et hors médiaLa communication média et hors média
La communication média et hors médiaoz ressourcesorg
 

Viewers also liked (15)

Agenda 6è b setmana 46 -novembre-curs 16-17
Agenda 6è b setmana 46 -novembre-curs 16-17Agenda 6è b setmana 46 -novembre-curs 16-17
Agenda 6è b setmana 46 -novembre-curs 16-17
 
4 Ways to Merge IBM i Data with Microsoft Excel
4 Ways to Merge IBM i Data with Microsoft Excel4 Ways to Merge IBM i Data with Microsoft Excel
4 Ways to Merge IBM i Data with Microsoft Excel
 
Agenda setmana 48 -nov-desembre-curs16-17
Agenda setmana 48 -nov-desembre-curs16-17Agenda setmana 48 -nov-desembre-curs16-17
Agenda setmana 48 -nov-desembre-curs16-17
 
Container communication on lattice #2
Container communication on lattice #2Container communication on lattice #2
Container communication on lattice #2
 
Sunset park, paul auster
Sunset park, paul austerSunset park, paul auster
Sunset park, paul auster
 
Agenda setmana 51 -desembre-curs16-17
Agenda setmana 51 -desembre-curs16-17Agenda setmana 51 -desembre-curs16-17
Agenda setmana 51 -desembre-curs16-17
 
El ordenador y sus componentes.
El ordenador y sus componentes.El ordenador y sus componentes.
El ordenador y sus componentes.
 
2do como-se-aprende-a-jugar-al-futbol
2do como-se-aprende-a-jugar-al-futbol2do como-se-aprende-a-jugar-al-futbol
2do como-se-aprende-a-jugar-al-futbol
 
Case histories luigi nespoli slogan
Case histories luigi nespoli sloganCase histories luigi nespoli slogan
Case histories luigi nespoli slogan
 
La Empresa Y Su Entorno
La Empresa Y Su EntornoLa Empresa Y Su Entorno
La Empresa Y Su Entorno
 
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...
Phát triển hoạt động thanh toán không dùng tiền mặt tại ngân hàng nông nghiệp...
 
Microsoft excel 2010 intermediated advanced
Microsoft excel 2010 intermediated advancedMicrosoft excel 2010 intermediated advanced
Microsoft excel 2010 intermediated advanced
 
Знаете ли вы сказки А.С. Пушкина
Знаете ли вы сказки А.С. ПушкинаЗнаете ли вы сказки А.С. Пушкина
Знаете ли вы сказки А.С. Пушкина
 
IT Service Catalog Examples
IT Service Catalog ExamplesIT Service Catalog Examples
IT Service Catalog Examples
 
La communication média et hors média
La communication média et hors médiaLa communication média et hors média
La communication média et hors média
 

Similar to Locks? We Don't Need No Stinkin' Locks - Michael Barker

エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理maruyama097
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersDevDay Dresden
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析Mr. Vengineer
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 

Similar to Locks? We Don't Need No Stinkin' Locks - Michael Barker (20)

エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for Developers
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
Marat-Slides
Marat-SlidesMarat-Slides
Marat-Slides
 
3
33
3
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析
RISC-V : Berkeley Boot Loader & Proxy Kernelのソースコード解析
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 

More from JAX London

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityJAX London
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisJAX London
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsJAX London
 
It's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisIt's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisJAX London
 
Worse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyWorse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyJAX London
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJAX London
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfJAX London
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter HiltonJAX London
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundJAX London
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberJAX London
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerJAX London
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundJAX London
 
Closures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderClosures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderJAX London
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJAX London
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsJAX London
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonJAX London
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaJAX London
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerJAX London
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...JAX London
 

More from JAX London (20)

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexity
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick Debois
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
 
It's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisIt's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick Debois
 
Worse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyWorse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin Henney
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha Gee
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter Hilton
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim Berglund
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave Gruber
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko Seeburger
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim Berglund
 
Closures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderClosures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel Winder
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk Pepperdine
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdams
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian Robinson
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Locks? We Don't Need No Stinkin' Locks - Michael Barker

  • 1. Locks? We don’t need no stinkin’ Locks! @mikeb2701 http://bad-concurrency.blogspot.com Image: http://subcirlce.co.uk
  • 2.
  • 5. Causality Causality Fear will keep the local systems inline. instructions - Grand Moff Wilhuff Tarkin
  • 6. Loads are not reordered with other loads. • Stores are not reordered with other stores. • Stores are not reordered with older loads. • In a multiprocessor system, memory ordering obeys causality (memory ordering respects transitive visibility). • In a multiprocessor system, stores to the same location have a total order. • In a multiprocessor system, locked instructions to the same location have a total order. • Loads and Stores are not reordered with locked instructions.
  • 9. public class AtomicLong extends Number implements Serializable { // ... private volatile long value; // ... /** * Sets to the given value. * * @param newValue the new value */ public final void set(long newValue) { value = newValue; } // ... }
  • 10. # {method} 'set' '(J)V' in 'java/util/concurrent/atomic/AtomicLong' # this: rsi:rsi = 'java/util/concurrent/atomic/AtomicLong' # parm0: rdx:rdx = long # [sp+0x20] (sp of caller) mov 0x8(%rsi),%r10d shl $0x3,%r10 cmp %r10,%rax jne 0x00007f1f410378a0 ; {runtime_call} xchg %ax,%ax nopl 0x0(%rax,%rax,1) xchg %ax,%ax push %rbp sub $0x10,%rsp nop mov %rdx,0x10(%rsi) lock addl $0x0,(%rsp) ;*putfield value ; - j.u.c.a.AtomicLong::set@2 (line 112) add $0x10,%rsp pop %rbp test %eax,0xa40fd06(%rip) # 0x00007f1f4b471000 ; {poll_return}
  • 11. public class AtomicLong extends Number implements Serializable { // setup to use Unsafe.compareAndSwapLong for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; // ... /** * Eventually sets to the given value. * * @param newValue the new value * @since 1.6 */ public final void lazySet(long newValue) { unsafe.putOrderedLong(this, valueOffset, newValue); } // ... }
  • 12. # {method} 'lazySet' '(J)V' in 'java/util/concurrent/atomic/ AtomicLong' # this: rsi:rsi = 'java/util/concurrent/atomic/AtomicLong' # parm0: rdx:rdx = long # [sp+0x20] (sp of caller) mov 0x8(%rsi),%r10d shl $0x3,%r10 cmp %r10,%rax jne 0x00007f1f410378a0 ; {runtime_call} xchg %ax,%ax nopl 0x0(%rax,%rax,1) xchg %ax,%ax push %rbp sub $0x10,%rsp nop mov %rdx,0x10(%rsi) ;*invokevirtual putOrderedLong ; - AtomicLong::lazySet@8 (line 122) add $0x10,%rsp pop %rbp test %eax,0xa41204b(%rip) # 0x00007f1f4b471000 ; {poll_return}
  • 13. public class AtomicInteger extends Number implements Serializable { // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; private volatile int value; //... public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } }
  • 14. # {method} 'compareAndSet' '(JJ)Z' in 'java/util/concurrent/ atomic/AtomicLong' # this: rsi:rsi = 'java/util/concurrent/atomic/AtomicLong' # parm0: rdx:rdx = long # parm1: rcx:rcx = long # [sp+0x20] (sp of caller) mov 0x8(%rsi),%r10d shl $0x3,%r10 cmp %r10,%rax jne 0x00007f6699037a60 ; {runtime_call} xchg %ax,%ax nopl 0x0(%rax,%rax,1) xchg %ax,%ax sub $0x18,%rsp mov %rbp,0x10(%rsp) mov %rdx,%rax lock cmpxchg %rcx,0x10(%rsi) sete %r11b movzbl %r11b,%r11d ;*invokevirtual compareAndSwapLong ; - j.u.c.a.AtomicLong::compareAndSet@9 (line 149) mov %r11d,%eax add $0x10,%rsp pop %rbp test %eax,0x91df935(%rip) # 0x00007f66a223e000 ; {poll_return}
  • 15. set() compareAndSet lazySet() 9 6.75 4.5 2.25 0 nanoseconds/op
  • 16. Example - Disruptor Multi-producer private void publish(Disruptor disruptor, long value) { long next = disruptor.next(); disruptor.setValue(next, value); disruptor.publish(next); }
  • 17. Example - Disruptor Multi-producer public long next() { long next; long current; do { current = nextSequence.get(); next = current + 1; while (next > (readSequence.get() + size)) { LockSupport.parkNanos(1L); continue; } } while (!nextSequence.compareAndSet(current, next)); return next; }
  • 18. Algorithm: Spin - 1 public void publish(long sequence) { long sequenceMinusOne = sequence - 1; while (cursor.get() != sequenceMinusOne) { // Spin } cursor.lazySet(sequence); }
  • 19. Spin - 1 25 18.75 million ops/sec 12.5 6.25 0 1 2 3 4 5 6 7 8 Producer Threads
  • 20. Algorithm: Co-Op public void publish(long sequence) { int counter = RETRIES; while (sequence - cursor.get() > pendingPublication.length()) { if (--counter == 0) { Thread.yield(); counter = RETRIES; } } long expectedSequence = sequence - 1; pendingPublication.set((int) sequence & pendingMask, sequence); if (cursor.get() >= sequence) { return; } long nextSequence = sequence; while (cursor.compareAndSet(expectedSequence, nextSequence)) { expectedSequence = nextSequence; nextSequence++; if (pendingPublication.get((int) nextSequence & pendingMask) != nextSequence) { break; } } }
  • 21. Spin - 1 Co-Op 30 22.5 million ops/sec 15 7.5 0 1 2 3 4 5 6 7 8 Producer Threads
  • 22. Algorithm: Buffer public long next() { long next; long current; do { current = cursor.get(); next = current + 1; while (next > (readSequence.get() + size)) { LockSupport.parkNanos(1L); continue; } } while (!cursor.compareAndSet(current, next)); return next; }
  • 23. Algorithm: Buffer public void publish(long sequence) { int publishedValue = (int) (sequence >>> indexShift); published.set(indexOf(sequence), publishedValue); } // Get Value int availableValue = (int) (current >>> indexShift); int index = indexOf(current); while (published.get(index) != availableValue) { // Spin }
  • 24. Spin - 1 Co-Op Buffer 70 52.5 million ops/sec 35 17.5 0 1 2 3 4 5 6 7 8 Threads
  • 26. Q&A • https://github.com/mikeb01/jax2012 • http://www.lmax.com/careers • http://www.infoq.com/presentations/Lock- free-Algorithms • http://www.youtube.com/watch? v=DCdGlxBbKU4

Editor's Notes

  1. - Concurrency is taught all wrong.\n- What is non-blocking concurrency.\n- Mechanical Sympathy, locks/mutexs are a completely artificial construct\n- MTs concurrency course blocking v. non-blocking.\n- Tools for non-blocking concurrency functions of the CPU, need to look at CPU architecture first.\n
  2. - Causality\n- Why CPUs/Compilers reorder\n
  3. - Java Memory Model provides serial consistency for race-free programs\n- As-if-serial\n- Disallows out of thin air values\n- First main-stream programming language to include a memory model (C/C++ combination of the CPU and whatever the compiler happens to do.\n
  4. \n
  5. \n
  6. \n
  7. - volatile\n- java.util.concurrent.atomic.*\n - Atomic<Long|Integer|Reference>\n - Atomic<Long|Integer|Reference>Array (why use over an array of atomics)\n - Atomic<Long|Integer|Reference>FieldUpdater (can be a bit slow)\n
  8. - Fight club\n- If you’re smart enough\n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. - Thread wake ups\n- Hard spin\n- Spin with yield\n- PAUSE instruction - please add to Java\n- MONITOR and MWAIT\n
  26. \n