Java concurrency API
By Franck Benault
Created 06/12/2015
Last update 22/11/2015
Java concurrency introduction
● Parallelism can speed up you program
– But is Java the best language for concurrency ?
Java concurrency links
● My examples in Github
– https://github.com/franck-benault/test-concurrence
Java concurrency plan
Goal of this presentation
● Goal
– Very simple presentation
● Focus on ExecutorService
Java concurrency : Basics threads
● Principle
– Class Worker implemented Runnable interface
– Worker w = new Worker(...) ;
– Thread t = new Thread(w) ;
– t.start() ;
– t.join() ; //wait until the end of the thread
● Problems
– Run() method does not return any information (return value, exception)
– How to manage a pool of threads ?
– Do not use this way anymore !
Java concurrency : Sleep
● Old way
– Thread.sleep(100);
● Since Java5
– TimeUnit.MILLISECONDS.sleep(100);
Java concurrency : show threads
with jvisualVM
Java concurrency : Basics
isSynchronized
● Key word
– On a bloc (with a parameter)
– On a method
● Thread safe
Java concurrency :
ExcecutorService
● Management of a pool of threads
● Accept Callable and Runnable
ExecutorService executor;
executor = Executors.newFixedThreadPool(threadPoolSize);
WorkerThread workerThread = new WorkerThread(...);
executor.submit(workerThread);
...
executor.shutdown();
while (!executor.isTerminated()) Thread.sleep(10);
Conclusion
● Let's start with concurrency in Java

Java concurrency

  • 1.
    Java concurrency API ByFranck Benault Created 06/12/2015 Last update 22/11/2015
  • 2.
    Java concurrency introduction ●Parallelism can speed up you program – But is Java the best language for concurrency ?
  • 3.
    Java concurrency links ●My examples in Github – https://github.com/franck-benault/test-concurrence
  • 4.
  • 5.
    Goal of thispresentation ● Goal – Very simple presentation ● Focus on ExecutorService
  • 6.
    Java concurrency :Basics threads ● Principle – Class Worker implemented Runnable interface – Worker w = new Worker(...) ; – Thread t = new Thread(w) ; – t.start() ; – t.join() ; //wait until the end of the thread ● Problems – Run() method does not return any information (return value, exception) – How to manage a pool of threads ? – Do not use this way anymore !
  • 7.
    Java concurrency :Sleep ● Old way – Thread.sleep(100); ● Since Java5 – TimeUnit.MILLISECONDS.sleep(100);
  • 8.
    Java concurrency :show threads with jvisualVM
  • 9.
    Java concurrency :Basics isSynchronized ● Key word – On a bloc (with a parameter) – On a method ● Thread safe
  • 10.
    Java concurrency : ExcecutorService ●Management of a pool of threads ● Accept Callable and Runnable ExecutorService executor; executor = Executors.newFixedThreadPool(threadPoolSize); WorkerThread workerThread = new WorkerThread(...); executor.submit(workerThread); ... executor.shutdown(); while (!executor.isTerminated()) Thread.sleep(10);
  • 11.
    Conclusion ● Let's startwith concurrency in Java