SlideShare a Scribd company logo
1 of 43
Download to read offline
Java Concurrency Idioms

         Alex Miller
Sharing



          Signals



 Work
Sharing
Data Race!


    A
Unsafe access
NOT safe for multi-threaded access:

public interface Counter
{
    int increment();
}


public class UnsafeCounter implements Counter {
    private int c = 0;

    public int increment() {
        return c++;
    }
}
volatile
Is this safe?


public class VolatileCounter implements Counter
{
    private volatile int c = 0;

    public int increment() {
        return c++;
    }
}
Synchronization


       A
synchronized


public class SynchronizedCounter
   implements Counter {

    private int c = 0;

    public synchronized int increment() {
        return c++;
    }
}
Atomic classes


public class AtomicCounter implements Counter
{
    private final AtomicInteger c =
                         new AtomicInteger(0);

    public int increment() {
        return c.incrementAndGet();
    }
}
ReentrantLock
public class ReentrantLockCounter
implements Counter
{
    private final Lock lock = new ReentrantLock();
    private int c = 0;

    public int increment() {
        lock.lock();
        try {
          return c++;
        } finally {
          lock.unlock();
        }
    }
}
ReentrantReadWriteLock
public class ReentrantRWLockCounter implements Counter {
    private final ReadWriteLock lock =
                             new ReentrantReadWriteLock();
    private int c = 0;
    public int increment() {
        lock.writeLock().lock();
        try {
          return c++;
        } finally {
          lock.writeLock().unlock();
        }
    }

    public int read() {
        lock.readLock().lock();
        try {
            return c;
        } finally {
            lock.readLock().unlock();
        }
    }
}
Encapsulation

 B

      A
Immutability

     A




     B
Immutability
Make field final, “mutator” methods return new
immutable instances.

public class Speed
{
    private final int milesPerHour;

    public Speed(int milesPerHour) {
       this.milesPerHour = milesPerHour;
    }

    public Speed sawCop() {
        return new Speed(this.milesPerHour - 10);
    }
}
Thread Confinement

        A




        B
ThreadLocal
ThreadLocal gives every Thread its own instance,
so no shared state.
public class ThreadLocalCounter implements Counter
{
    private final ThreadLocal<Integer> count =
      new ThreadLocal<Integer>();

    public ThreadLocalCounter() {
        count.set(Integer.valueOf(0));
    }

    public int increment() {
        Integer c = count.get();
        int next = c.intValue() + 1;
        count.set(Integer.valueOf(next));
        return next;
    }
}
code.run()
2 threads, 10000 reps
                  3,000


                  2,250
Total time (ms)




                  1,500


                   750


                     0
                          0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
                                              Write %

                          sychronized   RL(false)         RL(true)
                          RRWL(false)   RRWL(true)        synchronizedMap
                          Concurrent
2 threads, 10000 reps
                  130.0


                   97.5
Total time (ms)




                   65.0


                   32.5


                     0
                          0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
                                              Write %

                          sychronized         RL(false)         RRWL(false)
                          synchronizedMap     Concurrent
Signals
Direct Thread Interaction

         join()
join()
join() waits for another Thread to exit - signaling by
completion

Thread[] threads = new Thread[THREADS];

// start threads doing stuff

// wait for completion
for(int i=0; i<THREADS; i++) {
    threads[i].join();
}
Wait / Notify

notify()        wait()

           A
wait()
- wait() must occur in synchronization
- should occur in loop on the wait condition

synchronized(lock) {
    while(! someCondition) {
        lock.wait();
    }
}
notify() / notifyAll()
- notify() / notifyAll() must occur in synchronization



synchronized(lock) {
    lock.notifyAll();
}
Conditions

signal()               await()

           Condition
Condition waiting
Same as wait/notify but more flexible



Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();

// wait
lock.lock();
try {
    while(! theCondition) {
        condition.await(1, TimeUnit.SECONDS);
    }
} finally {
    lock.unlock();
}
Condition signaling


Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();

// wait
lock.lock();
try {
    condition.signalAll();
} finally {
    lock.unlock();
}
CyclicBarrier

                          N:
                await()
   Cyclic
   Barrier(N)
CyclicBarrier
Wait for known # of threads to reach barrier, then
release. Can be used multiple times.

int THREADS = 5;
CyclicBarrier barrier = new CyclicBarrier(THREADS);

// in thread, wait to start
barrier.await();

// do stuff

// in thread, wait to stop
barrier.await();
CountDownLatch

N:                                       M:
                               await()
     countDown()   CountDown
                   Latch(N)
CountDownLatch
Threads wait for count to reach 0



int COUNT = 5;
CountDownLatch latch = new CountDownLatch(COUNT);

// count down
latch.countDown();

// wait
latch.await();
code.run()
Work
Thread Pools
Queues



 ...
ExecutorService
ExecutorService
Executors has helper methods to create different
kinds of ExecutorServices backed by thread pools

// Create service backed by thread pool
ExecutorService service =
  Executors.newFixedThreadPool(THREADS);

// Define a Work that is Runnable
class Work implements Runnable {...}

// Submit work to the thread pool
service.execute(new Work());
CompletionService
CompletionService
CompletionService combines an ExecutorService
with a completion queue.

// Create completion service backed by thread pool
ExecutorService executor =
    Executors.newFixedThreadPool(THREADS);
CompletionService<Integer> completionService =
    new ExecutorCompletionService<Integer>(executor);

// Submit work
completionService.submit(
    new Callable<Integer>() { .. } );

// Wait for a result to be available
Future<Integer> result = completionService.take();
Integer value = result.get();   // blocks
code.run()
Questions?


Sharing



           Signals


 Work
Blog: http://tech.puredanger.com

Job: http://terracotta.org

Twitter: http://twitter.com/puredanger




                                         All content © 2008 by Alex Miller
                                         Photos from iStockPhoto.com

More Related Content

What's hot

Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsJussi Pohjolainen
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Hyuk Hur
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyIván López Martín
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 

What's hot (20)

Thread
ThreadThread
Thread
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
04 threads
04 threads04 threads
04 threads
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Threads
ThreadsThreads
Threads
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with Groovy
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 

Viewers also liked

Disruptor tools in action
Disruptor   tools in actionDisruptor   tools in action
Disruptor tools in actionMichael Barker
 
The Etsy Shard Architecture: Starts With S and Ends With Hard
The Etsy Shard Architecture: Starts With S and Ends With HardThe Etsy Shard Architecture: Starts With S and Ends With Hard
The Etsy Shard Architecture: Starts With S and Ends With Hardjgoulah
 
The 8051 assembly language
The 8051 assembly languageThe 8051 assembly language
The 8051 assembly languagehemant meena
 
Polymer & the web components revolution 6:25:14
Polymer & the web components revolution 6:25:14Polymer & the web components revolution 6:25:14
Polymer & the web components revolution 6:25:14mattsmcnulty
 
Downtown & Infill Tax Increment Districts: Strategies for Success
Downtown & Infill Tax Increment Districts: Strategies for SuccessDowntown & Infill Tax Increment Districts: Strategies for Success
Downtown & Infill Tax Increment Districts: Strategies for SuccessVierbicher
 
Appraisal and Performance Management in Schools - A practical approach
Appraisal and Performance Management in Schools - A practical approachAppraisal and Performance Management in Schools - A practical approach
Appraisal and Performance Management in Schools - A practical approachMark S. Steed
 
The Economics of Green Building
The Economics of Green BuildingThe Economics of Green Building
The Economics of Green Buildingnilskok
 
mySQL - INSERT INTO
mySQL - INSERT INTOmySQL - INSERT INTO
mySQL - INSERT INTOlehrerfreund
 
Increment letter format
Increment letter formatIncrement letter format
Increment letter formatDeepti Joshi
 
Comment être agile dans un contexte non lié aux TI ?
Comment être agile dans un contexte non lié aux TI ?Comment être agile dans un contexte non lié aux TI ?
Comment être agile dans un contexte non lié aux TI ?Pyxis Technologies
 
Convegno la mela nel mondo interpoma bz - 16-11-2012 1+2 - martin thalheime...
Convegno la mela nel mondo   interpoma bz - 16-11-2012 1+2 - martin thalheime...Convegno la mela nel mondo   interpoma bz - 16-11-2012 1+2 - martin thalheime...
Convegno la mela nel mondo interpoma bz - 16-11-2012 1+2 - martin thalheime...Image Line
 
area econòmica i patrimonial
area econòmica i patrimonialarea econòmica i patrimonial
area econòmica i patrimonialSandro
 
Canvi climàtic: Efectes i percepció social
Canvi climàtic: Efectes i percepció socialCanvi climàtic: Efectes i percepció social
Canvi climàtic: Efectes i percepció socialJosep Lluís Ruiz
 
Downtown & Infill Tax Increment Districts
Downtown & Infill Tax Increment DistrictsDowntown & Infill Tax Increment Districts
Downtown & Infill Tax Increment DistrictsVierbicher
 
Le Lean Product Management présenté au LeanKanban Day 2015
Le Lean Product Management présenté au LeanKanban Day 2015Le Lean Product Management présenté au LeanKanban Day 2015
Le Lean Product Management présenté au LeanKanban Day 2015Sébastien Sacard
 

Viewers also liked (20)

Disruptor tools in action
Disruptor   tools in actionDisruptor   tools in action
Disruptor tools in action
 
The Etsy Shard Architecture: Starts With S and Ends With Hard
The Etsy Shard Architecture: Starts With S and Ends With HardThe Etsy Shard Architecture: Starts With S and Ends With Hard
The Etsy Shard Architecture: Starts With S and Ends With Hard
 
Trial set
Trial setTrial set
Trial set
 
The 8051 assembly language
The 8051 assembly languageThe 8051 assembly language
The 8051 assembly language
 
Polymer & the web components revolution 6:25:14
Polymer & the web components revolution 6:25:14Polymer & the web components revolution 6:25:14
Polymer & the web components revolution 6:25:14
 
Conflict Resolution In Kai
Conflict Resolution In KaiConflict Resolution In Kai
Conflict Resolution In Kai
 
Agile Development
Agile DevelopmentAgile Development
Agile Development
 
Downtown & Infill Tax Increment Districts: Strategies for Success
Downtown & Infill Tax Increment Districts: Strategies for SuccessDowntown & Infill Tax Increment Districts: Strategies for Success
Downtown & Infill Tax Increment Districts: Strategies for Success
 
Appraisal and Performance Management in Schools - A practical approach
Appraisal and Performance Management in Schools - A practical approachAppraisal and Performance Management in Schools - A practical approach
Appraisal and Performance Management in Schools - A practical approach
 
The Economics of Green Building
The Economics of Green BuildingThe Economics of Green Building
The Economics of Green Building
 
mySQL - INSERT INTO
mySQL - INSERT INTOmySQL - INSERT INTO
mySQL - INSERT INTO
 
Increment letter format
Increment letter formatIncrement letter format
Increment letter format
 
Comment être agile dans un contexte non lié aux TI ?
Comment être agile dans un contexte non lié aux TI ?Comment être agile dans un contexte non lié aux TI ?
Comment être agile dans un contexte non lié aux TI ?
 
Convegno la mela nel mondo interpoma bz - 16-11-2012 1+2 - martin thalheime...
Convegno la mela nel mondo   interpoma bz - 16-11-2012 1+2 - martin thalheime...Convegno la mela nel mondo   interpoma bz - 16-11-2012 1+2 - martin thalheime...
Convegno la mela nel mondo interpoma bz - 16-11-2012 1+2 - martin thalheime...
 
Scrum Guide
Scrum GuideScrum Guide
Scrum Guide
 
area econòmica i patrimonial
area econòmica i patrimonialarea econòmica i patrimonial
area econòmica i patrimonial
 
Lliço5 Cinèticaquímica
Lliço5 CinèticaquímicaLliço5 Cinèticaquímica
Lliço5 Cinèticaquímica
 
Canvi climàtic: Efectes i percepció social
Canvi climàtic: Efectes i percepció socialCanvi climàtic: Efectes i percepció social
Canvi climàtic: Efectes i percepció social
 
Downtown & Infill Tax Increment Districts
Downtown & Infill Tax Increment DistrictsDowntown & Infill Tax Increment Districts
Downtown & Infill Tax Increment Districts
 
Le Lean Product Management présenté au LeanKanban Day 2015
Le Lean Product Management présenté au LeanKanban Day 2015Le Lean Product Management présenté au LeanKanban Day 2015
Le Lean Product Management présenté au LeanKanban Day 2015
 

Similar to Java Concurrency Idioms

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
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
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 

Similar to Java Concurrency Idioms (20)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
分散式系統
分散式系統分散式系統
分散式系統
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
java sockets
 java sockets java sockets
java sockets
 
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
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 

More from Alex Miller

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Alex Miller
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream ProcessingAlex Miller
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinAlex Miller
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojureAlex Miller
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebAlex Miller
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with ZippersAlex Miller
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative SoftwareAlex Miller
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your CacheAlex Miller
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The CloudAlex Miller
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleAlex Miller
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow TestAlex Miller
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009Alex Miller
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with TerracottaAlex Miller
 
Project Fortress
Project FortressProject Fortress
Project FortressAlex Miller
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns ReconsideredAlex Miller
 

More from Alex Miller (20)

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream Processing
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/join
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic Web
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At Scale
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow Test
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
 
Cold Hard Cache
Cold Hard CacheCold Hard Cache
Cold Hard Cache
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Java Concurrency Idioms

  • 2. Sharing Signals Work
  • 5. Unsafe access NOT safe for multi-threaded access: public interface Counter { int increment(); } public class UnsafeCounter implements Counter { private int c = 0; public int increment() { return c++; } }
  • 6. volatile Is this safe? public class VolatileCounter implements Counter { private volatile int c = 0; public int increment() { return c++; } }
  • 8. synchronized public class SynchronizedCounter implements Counter { private int c = 0; public synchronized int increment() { return c++; } }
  • 9. Atomic classes public class AtomicCounter implements Counter { private final AtomicInteger c = new AtomicInteger(0); public int increment() { return c.incrementAndGet(); } }
  • 10. ReentrantLock public class ReentrantLockCounter implements Counter { private final Lock lock = new ReentrantLock(); private int c = 0; public int increment() { lock.lock(); try { return c++; } finally { lock.unlock(); } } }
  • 11. ReentrantReadWriteLock public class ReentrantRWLockCounter implements Counter { private final ReadWriteLock lock = new ReentrantReadWriteLock(); private int c = 0; public int increment() { lock.writeLock().lock(); try { return c++; } finally { lock.writeLock().unlock(); } } public int read() { lock.readLock().lock(); try { return c; } finally { lock.readLock().unlock(); } } }
  • 14. Immutability Make field final, “mutator” methods return new immutable instances. public class Speed { private final int milesPerHour; public Speed(int milesPerHour) { this.milesPerHour = milesPerHour; } public Speed sawCop() { return new Speed(this.milesPerHour - 10); } }
  • 16. ThreadLocal ThreadLocal gives every Thread its own instance, so no shared state. public class ThreadLocalCounter implements Counter { private final ThreadLocal<Integer> count = new ThreadLocal<Integer>(); public ThreadLocalCounter() { count.set(Integer.valueOf(0)); } public int increment() { Integer c = count.get(); int next = c.intValue() + 1; count.set(Integer.valueOf(next)); return next; } }
  • 18. 2 threads, 10000 reps 3,000 2,250 Total time (ms) 1,500 750 0 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Write % sychronized RL(false) RL(true) RRWL(false) RRWL(true) synchronizedMap Concurrent
  • 19. 2 threads, 10000 reps 130.0 97.5 Total time (ms) 65.0 32.5 0 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Write % sychronized RL(false) RRWL(false) synchronizedMap Concurrent
  • 22. join() join() waits for another Thread to exit - signaling by completion Thread[] threads = new Thread[THREADS]; // start threads doing stuff // wait for completion for(int i=0; i<THREADS; i++) { threads[i].join(); }
  • 24. wait() - wait() must occur in synchronization - should occur in loop on the wait condition synchronized(lock) { while(! someCondition) { lock.wait(); } }
  • 25. notify() / notifyAll() - notify() / notifyAll() must occur in synchronization synchronized(lock) { lock.notifyAll(); }
  • 26. Conditions signal() await() Condition
  • 27. Condition waiting Same as wait/notify but more flexible Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); // wait lock.lock(); try { while(! theCondition) { condition.await(1, TimeUnit.SECONDS); } } finally { lock.unlock(); }
  • 28. Condition signaling Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); // wait lock.lock(); try { condition.signalAll(); } finally { lock.unlock(); }
  • 29. CyclicBarrier N: await() Cyclic Barrier(N)
  • 30. CyclicBarrier Wait for known # of threads to reach barrier, then release. Can be used multiple times. int THREADS = 5; CyclicBarrier barrier = new CyclicBarrier(THREADS); // in thread, wait to start barrier.await(); // do stuff // in thread, wait to stop barrier.await();
  • 31. CountDownLatch N: M: await() countDown() CountDown Latch(N)
  • 32. CountDownLatch Threads wait for count to reach 0 int COUNT = 5; CountDownLatch latch = new CountDownLatch(COUNT); // count down latch.countDown(); // wait latch.await();
  • 34. Work
  • 38. ExecutorService Executors has helper methods to create different kinds of ExecutorServices backed by thread pools // Create service backed by thread pool ExecutorService service = Executors.newFixedThreadPool(THREADS); // Define a Work that is Runnable class Work implements Runnable {...} // Submit work to the thread pool service.execute(new Work());
  • 40. CompletionService CompletionService combines an ExecutorService with a completion queue. // Create completion service backed by thread pool ExecutorService executor = Executors.newFixedThreadPool(THREADS); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor); // Submit work completionService.submit( new Callable<Integer>() { .. } ); // Wait for a result to be available Future<Integer> result = completionService.take(); Integer value = result.get(); // blocks
  • 42. Questions? Sharing Signals Work
  • 43. Blog: http://tech.puredanger.com Job: http://terracotta.org Twitter: http://twitter.com/puredanger All content © 2008 by Alex Miller Photos from iStockPhoto.com