SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
JACCRA
http://frankappiahnsiah.wordpress.com




Introduction to Java Concurrency


                Frank Appiah
             Software Developer
                Genkey Corp.
RoadMap
 Background
 Concept
 Demo
What is Java Concurrency ?
 Concurrency means existing or in operation at the same time
  or together.
 Java provides :
          1. Lock
          2. Thread and Thread Management
          3. Atomic
 It is in the package java.util.concurrency
RoadMap
 Background
 Concept
 Demo
LOCKS
 Package: java.util.concurrent.locks
What are the locks in Java?
 Lock
  Lock implementations provide more extensive locking operations
  than can be obtained using synchronized methods and statements.
  They allow more flexible structuring, may have quite different
  properties, and may support multiple associated Condition
  objects.

 ReadWriteLock
  A ReadWriteLock maintains a pair of associated locks, one for
  read-only operations and one for writing. The read lock may be
  held simultaneously by multiple reader threads, so long as there
  are no writers. The write lock is exclusive.
Lock
 A lock is a tool for controlling access to a shared resource by
  multiple threads. Commonly, a lock provides exclusive
  access to a shared resource: only one thread at a time can
  acquire the lock and all access to the shared resource requires
  that the lock be acquired first. However, some locks may
  allow concurrent access to a shared resource, such as the
  read lock of a ReadWriteLock.
ReentrantLock
 A reentrant mutual exclusion Lock with the same basic
  behavior and semantics as the implicit monitor lock accessed
  using synchronized methods and statements, but with
  extended capabilities.
Demo
 ReentrantLock reentrantLock=new ReentrantLock();


   public int getNextSequenceID()
   {
    return getNewValue();
   }
                                                     Lock acquired
   private int getNewValue()
   {
    reentrantLock.lock();
    value+=1;
   reentrantLock.unlock();
   return value;                                     Lock unacquired
   }
Different Implementation
(edu.emory.mathcs.backport)

 To use this implementation of Java Concurrency
Just append the package name below to all java.util.concurrent
  package classes.
 edu.emory.mathcs.backport
Creating a Lock Factory with both
  implementations
   Check to see if edu.emory.mathcs.backport implementation
     is available


static {
      try {

Class.forName("edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock");
                               backportConcurrentPresent = true;
                    } catch (ClassNotFoundException ex) {
                               backportConcurrentPresent = false;
                    }
          }
Creating a Lock Implementation


   if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) {

          return new JdkConcurrentLock(timeoutSeconds);
                         } else if (backportConcurrentPresent) {

       return new BackportConcurrentLock(timeoutSeconds);
ATOMICS
 Package: java.util.concurrent.atomic
Uses
It can be
 use as an atomic update flag (AtomicBoolean)
 use as a sequential atomic counter (AtomicInteger)
 use as an atomically incremented sequence
   number(AtomicLong)
 use to hold an atomic reference to an object
   (AtomicReference<V>,V is the reference object)
Demo

 private AtomicLong atomic;
       public AtomicTest(long intialValue)
      {
     atomic=new AtomicLong(intialValue);
       }

   public Long increment()
   {
     return atomic.incrementAndGet();
   }
Concurrent
           Threads
 Package: java.util.concurrent
What to look at?
 ThreadFactory
 ThreadPoolExecutor
 Callable (special form of Runnable class)
ThreadFactory
 Implement a custom thread factory

     public class CustomThreadFactory implements ThreadFactory


 There is a single method called newThread that takes
  Runnable as its parameter
 Purpose : To create a new thread for the
  ThreadPoolExecutor when a new work requires a thread.
How to create a custom
ThreadFactory?

  public class CustomThreadFactory extends CustomThreadCreator implements
                               ThreadFactory{

                    public CustomThreadFactory { super(); }

            public CustomThreadFactory(String threadNamePrefix) {
                          super(threadNamePrefix); }

                    public Thread newThread(Runnable r) {
                              return createThread(r);
                                      }
                                         }
ThreadPoolExecutor
 It can be schedule or not
 For scheduled thread executor
  use :ScheduledThreadPoolExecutor class.
 A custom thread pool executor may be preferable.
Demo
 Lets go to the code
 Walking through
Callable
 This just like Runnable but this returns a result of the
  execution task.
 Call the submit method of ThreadPoolExecutor instance and
  pass in the Callable interface implementation.
Thread Management
ThreadPoolExecutor methods for management:
 getTaskCount()
 getCompletedTaskCount()
 purge()
 shutdown()
 shutdownNow()
Further Reading
 Tutorial
 Download

Contenu connexe

Tendances

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization ConstructsSasha Kravchuk
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 

Tendances (20)

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Threads in java
Threads in javaThreads in java
Threads in java
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 

Similaire à Introduction+To+Java+Concurrency

Similaire à Introduction+To+Java+Concurrency (20)

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java tips
Java tipsJava tips
Java tips
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Lecture10
Lecture10Lecture10
Lecture10
 
Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java adv
Java advJava adv
Java adv
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Advance Java
Advance JavaAdvance Java
Advance Java
 

Introduction+To+Java+Concurrency

  • 2. http://frankappiahnsiah.wordpress.com Introduction to Java Concurrency Frank Appiah Software Developer Genkey Corp.
  • 4. What is Java Concurrency ?  Concurrency means existing or in operation at the same time or together.  Java provides : 1. Lock 2. Thread and Thread Management 3. Atomic  It is in the package java.util.concurrency
  • 7. What are the locks in Java?  Lock Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.  ReadWriteLock A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
  • 8. Lock  A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.
  • 9. ReentrantLock  A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
  • 10. Demo  ReentrantLock reentrantLock=new ReentrantLock(); public int getNextSequenceID() { return getNewValue(); } Lock acquired private int getNewValue() { reentrantLock.lock(); value+=1; reentrantLock.unlock(); return value; Lock unacquired }
  • 11. Different Implementation (edu.emory.mathcs.backport)  To use this implementation of Java Concurrency Just append the package name below to all java.util.concurrent package classes.  edu.emory.mathcs.backport
  • 12. Creating a Lock Factory with both implementations  Check to see if edu.emory.mathcs.backport implementation is available static { try { Class.forName("edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock"); backportConcurrentPresent = true; } catch (ClassNotFoundException ex) { backportConcurrentPresent = false; } }
  • 13. Creating a Lock Implementation if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) { return new JdkConcurrentLock(timeoutSeconds); } else if (backportConcurrentPresent) { return new BackportConcurrentLock(timeoutSeconds);
  • 15. Uses It can be  use as an atomic update flag (AtomicBoolean)  use as a sequential atomic counter (AtomicInteger)  use as an atomically incremented sequence number(AtomicLong)  use to hold an atomic reference to an object (AtomicReference<V>,V is the reference object)
  • 16. Demo private AtomicLong atomic; public AtomicTest(long intialValue) { atomic=new AtomicLong(intialValue); } public Long increment() { return atomic.incrementAndGet(); }
  • 17. Concurrent Threads  Package: java.util.concurrent
  • 18. What to look at?  ThreadFactory  ThreadPoolExecutor  Callable (special form of Runnable class)
  • 19. ThreadFactory  Implement a custom thread factory public class CustomThreadFactory implements ThreadFactory  There is a single method called newThread that takes Runnable as its parameter  Purpose : To create a new thread for the ThreadPoolExecutor when a new work requires a thread.
  • 20. How to create a custom ThreadFactory? public class CustomThreadFactory extends CustomThreadCreator implements ThreadFactory{ public CustomThreadFactory { super(); } public CustomThreadFactory(String threadNamePrefix) { super(threadNamePrefix); } public Thread newThread(Runnable r) { return createThread(r); } }
  • 21. ThreadPoolExecutor  It can be schedule or not  For scheduled thread executor use :ScheduledThreadPoolExecutor class.  A custom thread pool executor may be preferable.
  • 22. Demo  Lets go to the code  Walking through
  • 23. Callable  This just like Runnable but this returns a result of the execution task.  Call the submit method of ThreadPoolExecutor instance and pass in the Callable interface implementation.
  • 24. Thread Management ThreadPoolExecutor methods for management:  getTaskCount()  getCompletedTaskCount()  purge()  shutdown()  shutdownNow()