SlideShare a Scribd company logo
1 of 18
Download to read offline
Concurrent
Programming
   May 6, 2010
Agenda

ā€¢ Motivational Examples
ā€¢ Computing Model
ā€¢ Race Conditions
ā€¢ Deadlocks
ā€¢ Resources
                    2
Sleeping Barber
      ā€œBAUā€ Process
      Barber cuts hair
      When ļ¬nished, he checks the waiting room
      If no one is there, he goes to sleep in the chair
      Customers arriving while the barber is asleep wake the
      barber


          What can go wrong?
          Barber ļ¬nishes, walks to waiting room
          Customer arrives and goes to wake the barber
          They do not see each other, return and wait
          indeļ¬nitely



          3
Dining Philosophers
                               ā€œBAUā€ Process
                               Philosophers alternate between thinking and eating
                               Two forks are required to eat spaghetti
                               When ļ¬nished thinking, philosophers seek forks
                               When ļ¬nished eating, philosophers put forks down


                                     What can go wrong?
                                     Process of picking up, putting down forks can
                                     result in each philosopher holding one fork -
                                     none can eat


     Dining Philosophers Demo
 http://www.doc.ic.ac.uk/~jnm/concurrency/classes/Diners/Diners.html
                                     4
Computing
                   Canonical Model
                   ā€¢ Processes spawn threads to do work
                   ā€¢ Threads maintain local state but can also
                       access shared state
                   ā€¢   Threads can be active, suspended, blocked
                       waiting for resources or sleeping
                   ā€¢   Threads execute concurrently - truly
                       concurrently in multi-processor
                       environments, virtually concurrently in single-
                       processor environments
                   ā€¢   Thread scheduling is managed by the parent
                       process, operating system and / or application
                   ā€¢   Sequencing of operations across different
                       threads is in general unpredictable


Shared State
                   5
Simple Computing Problem
      Bad Timing                                  Web App Hit Counter
                                                  ā€¢ Multi-threaded web app wants to maintain a
                                                       count of the number of hits it gets
        Read counter
                                                  ā€¢    Shared state is used to maintain the count
                                                  ā€¢    Request processing threads update the count
                                                       each time they process a request
                                                  ā€¢    Under heavy load, the app seems to ā€œmissā€
        Read counter                                   some hits. Why?

     Assign counter+1


                                                      public void increment() {
      Assign counter+1
                                                          count = count + 1;
                                                      }

Badness results from B reading the counter while A is in process of updating it. This is an example of a
race condition.
                                                  6
Solution
     Semaphore                            Keep B out while A updates
                                      ā€¢ Could make ā€œcount++ā€ operation atomic (i.e. unable to
                                           be interrupted.) The JDK 1.5 AtomicInteger class
                                           does this.
       Close the door                 ā€¢    More general solution is to synchronize access to the
                                           shared resource
                                      ā€¢    Using a semaphore, Thread A signals exclusive access
                                           to the critical section of code that does the update
       Knock on door
                                      ā€¢    Simplest semaphore is a mutex (mutual exclusion - just
                                           one allowed in at a time) and simplest implementation
    Update, open door
                                           in Java is via the synchronized keyword


      Close door, update
                                      public synchronized void increment() {
                                          count = count + 1;
                                      }

Note that the same solution would work for the sleeping barber (close door to waiting room)
                                                 7
Synchronized Keyword in Java
   ā€¢   Acts as a mutex on blocks of code

   ā€¢   Can protect entire methods, or blocks within methods

   ā€¢   Uses the concept of a monitor on an object to represent the mutex - code entering a
       synchronized block acquires an object monitor

   ā€¢   When no object is speciļ¬ed, the monitor on the object executing the code is implied

   ā€¢   Synchronization locks are reentrant - i.e., if a thread owns an objectā€™s monitor and it enters
       another method that requires the same monitor, it is allowed in

   ā€¢   When a thread leaves a synchronized block, it releases the associated monitor (even if an
       exception occurs)

                        Parent objectā€™s monitor                                Fuā€™s monitor
public synchronized void foo() {       public void foo() {               public void foo() {
    fu.bar();                              synchronized (this) {             synchronized (fu) {
}                                              fu.bar();                         fu.bar();
                                           }                                 }
                                       }                                 }

                                                  8
Concurrent Object Access
                                   Method




                                   Object


                                  Threads
                        Object References
When multiple threads share references to the same object, they can concurrently call the same
method on the object, unless synchronization prevents this. A class is thread-safe if concurrently
executing threads can safely hold references to instances of the class.
                                                9
Programmerā€™s Challenge:
     Situational Awareness
 ā€¢    The question always needs to be asked, ā€œwill multiple threads hold references to instances
      of this class at the same time?ā€ Unfortunately, it is sometimes hard to know.
 ā€¢    Most common use cases involving concurrent access are created by application
      containers, often in conjunction with application frameworks. Containers manage
      threads and frameworks instantiate objects. Fun begins when the Singleton Pattern is
      used by the framework.


Primitive Survival Technique: Avoid the bad neighborhood altogether

ā€¢    Keep is Stateless Stupid (KISS) - avoid maintaining state across method calls
ā€¢    Prefer immutable objects - only ļ¬nal ļ¬elds, all set by constructors
ā€¢    Never spawn threads - let the container manage them
ā€¢    Use tested, thread-safe resource providers (e.g. databases) to maintain state (when you are
     dragged kicking and screaming into acknowledging the need to maintain state at all)
ā€¢    Encapsulate parameters needed by methods in value objects and pass these to/from methods
     instead of relying on instance ļ¬elds

                                                 10
Anatomical Example
public class Foo {
    public static final int HOSIERY_THRESHOLD = 1000;               No worries
    private boolean fubar;
    ...
    public void hose(int ways) {
                                                                     Careful!
        int newWays = generateNewWays();
        if (ways + newWays > HOSIERY_THRESHOLD) {
            fubar = true;
        }
    }




ā€¢   Static ļ¬nal ļ¬elds are initialized when the class is loaded and donā€™t change thereafter, so all
    threads see the same values - threadsafe
ā€¢   Method parameters are provided to each thread on the call stack and are only visible to
    that thread for the duration of the method - threadsafe
ā€¢   Local variables declared within methods are only visible to the thread activating the
    method for the duration of the method - threadsafe
ā€¢   Class member ļ¬elds are visible to all threads, so if two threads can be inside a method
    that uses a member ļ¬eld at the same time, care must be taken to synchronize access
                                                11
Example - Struts 1.x Actions
         Servlet Container                                                          1. When the web app starts, it loads
                 ActionServlet                                                         the Struts ActionServlet (one
                                                                                       ActionServlet instance per web
                       FooAction
                                                                                       application - a singleton)

                        BarAction
                                                                                    2. When the ActionServlet is
                                                                                       initialized, it reads its
                                                                                       conļ¬guration and loads one
                                                                                       instance each of the Action
                                                                                       classes deļ¬ned in its conļ¬guration
                      FubarAction                                                      (more singletons)
                                                                                    3. When browser requests arrive,
                                                                                       the container assigns processing
                                                                                       threads to requests and passes
                                                                                       requests mapped to the Struts
                                                                                       application to the Struts
                                                                                       ActionServlet instance

     4. The Struts ActionServlet calls perform(ActionMapping mapping, ActionForm form, HttpServletRequest
        request, HttpServletResponse response) on the single Action instance that it uses for all requests


Consequence: Struts Action classes must be threadsafe!
rtfm://struts.apache.org/1.0.2/userGuide/building_controller.html#action_classes
                                                                               12
Struts 1.x Example (Cont.)
Inside a Struts Action Class:
private String successPath = null;
private String failedPath = null;
private String maxAttemptsPath = null;

public ActionForward perform( ActionMapping mapping, ActionForm
        form, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

    // Set forward paths, using request information
    setForwardPaths(mapping, request );
  ...
Depending on processing outcome, forward to configured path
}

private void setForwardPaths(ActionMapping mapping, HttpServletRequest request) {
  ...
  successPath = ...
  failedPath = ...
  maxAttemptsPath = ...
}


 Problem: If two requests for this action are processed concurrently, and the
 computed forward paths are different, control can be misdirected.
                                             13
Struts 1.x Example - Fix
private String successPath = null;
private String failedPath = null;
private String maxAttemptsPath = null;

public ActionForward perform( ActionMapping mapping, ActionForm
        form, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

    // Set forward paths, using request information
    ForwardPaths forwardPaths = getForwardPaths(mapping,request);
    String successPath = forwardPaths.getSuccessPath();
    String failedPath = forwardPaths.getFailedPath();
    String maxAttemptsPath = forwardPaths.getMaxAttemptsPath();
  ...
Depending on processing outcome, forward to configured path
}

private ForwardPaths setForwardPaths(ActionMapping mapping, HttpServletRequest request) {
   // Compute and store local variables success, failed, maxAttempt representing paths
   ...
   return new ForwardPaths(success, failed, maxAttempts);
}


 Eliminating the member ļ¬elds makes the class threadsafe. Introduction of a value object
 (ForwardPaths inner class not shown) enables data to be safely transmitted to/from the private
 helper method.
                                             14
Deadlock
                  Thread 1                              Thread 2

                   Acquire lock A

                                                        Acquire lock B

                  Block waiting to
                   acquire lock B


                                                        Block waiting to
                                                         acquire lock A



Thread 1 canā€™t proceed until it gets the lock that Thread 2 is holding on B. Thread 2 canā€™t
proceed until it gets the lock that Thread 1 is holding on A. No other threads can do anything
that requires either lock. This kind of situation can cause application servers to ā€œhang.ā€

                                               15
DeadLock Example
Apache Commons Pool provides        Maintenance Thread           Client Thread
a generic object pooling API and
implementations
Apache Commons DBCP is a            Acquire pool lock
database connection pool that                                  Acquire factory
uses Commons Pool as its                                            lock
underlying object pool
                                     Block waiting to
When used together, versions         acquire factory
1.2-1.4 of Commons Pool and                lock
1.1-1.2.x of Commons DBCP
could create a deadlock (tracked                                Block waiting to
as DBCP-44 in ASF JIRA)                                        acquire pool lock
Source of the deadlock:
Contention between client
threads borrowing / returning       Resolution: Modify pool code to move all
objects and a maintenance thread    invocations of factory methods outside of
for locks on the pool and objects   synchronized scope (so lock in 0 is released before
used by the poolā€™s object factory   step 2 is attempted)
                                        16
Avoiding Deadlocks
Rule number 0: Leave concurrency management to external resource providers or fully
tested frameworks - try to design around the need for synchronization
Rule number 1: When holding a lock, never call any methods that require other locks
Would completely eliminate possibility of deadlock; but unfortunately not always possible
Rule number 2: When you must use multiple locks to perform actions in your application,
establish a hierarchy of locks and always acquire locks in the order determined by the
hierarchy
Rule number 3: Maintain a complete and consistent execution model of application
subsystems and make explicit (via both documentation and test cases) invariants that enforce
lock hierarchy and/or prevent contention for locks
Rule number 4: Pay special attention to exception processing, especially when using explicit
locks (i.e., objects that implement the Lock interface) - make sure locks are released on all
execution paths




                                             17
Resources
Java Threads, Scott Oaks, Henry Wong (http://oreilly.com/catalog/9780596007829/index.html?
CMP=ILL-4GV796923290)
The Little Book of Semaphores, Allen B Downey (http://greenteapress.com/semaphores/)
ā€œConcurrent Programming with J2SE 1.5ā€ (http://java.sun.com/developer/technicalArticles/
J2SE/concurrency/) Also read carefully the class javadoc for all of the classes in the
concurrency package
ā€œHierarchical Ordering of Sequential Processesā€, Edsker Dijkstra, working paper (http://
userweb.cs.utexas.edu/users/EWD/ewd03xx/EWD310.PDF)
ā€œSequential Programming vs Concurrent Programmingā€, Jerry Cain (http://academicearth.org/
lectures/sequential-programming-concurrent-programming)
A little ā€œOTā€:
ā€œOn the Nature of Time - Why does Nature Abhor Deadlocks?ā€, Christine Cordula Dantas
(http://www.fqxi.org/data/essay-contest-ļ¬les/Dantas_Nattime2_1.pdf?
phpMyAdmin=0c371ccdae9b5ff3071bae814fb4f9e9)



                                            18

More Related Content

Similar to Concurrent Programming Techniques

Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
Ā 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceDeon Huang
Ā 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVMManish Pandit
Ā 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
Ā 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
Ā 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
Ā 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
Ā 
multithreading
multithreadingmultithreading
multithreadingRajkattamuri
Ā 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
Ā 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
Ā 
Multithreading
MultithreadingMultithreading
MultithreadingF K
Ā 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming LanguageJunji Zhi
Ā 
Asynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionAsynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionPyData
Ā 
Java gc
Java gcJava gc
Java gcNiit
Ā 
Java Garbage Collection
Java Garbage CollectionJava Garbage Collection
Java Garbage CollectionVinay H G
Ā 

Similar to Concurrent Programming Techniques (20)

Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Ā 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Ā 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
Ā 
Adsa u4 ver 1.0
Adsa u4 ver 1.0Adsa u4 ver 1.0
Adsa u4 ver 1.0
Ā 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
Ā 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
Ā 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
Ā 
Thread model of java
Thread model of javaThread model of java
Thread model of java
Ā 
Java
JavaJava
Java
Ā 
Multi threading
Multi threadingMulti threading
Multi threading
Ā 
multithreading
multithreadingmultithreading
multithreading
Ā 
Java
JavaJava
Java
Ā 
Java threading
Java threadingJava threading
Java threading
Ā 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Ā 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ā 
Multithreading
MultithreadingMultithreading
Multithreading
Ā 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
Ā 
Asynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionAsynchronous Python A Gentle Introduction
Asynchronous Python A Gentle Introduction
Ā 
Java gc
Java gcJava gc
Java gc
Ā 
Java Garbage Collection
Java Garbage CollectionJava Garbage Collection
Java Garbage Collection
Ā 

More from Phil Steitz

Programming Math in Java - Lessons from Apache Commons Math
Programming Math in Java - Lessons from Apache Commons MathProgramming Math in Java - Lessons from Apache Commons Math
Programming Math in Java - Lessons from Apache Commons MathPhil Steitz
Ā 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdatePhil Steitz
Ā 
Commons Nabla
Commons NablaCommons Nabla
Commons NablaPhil Steitz
Ā 
Leadership model
Leadership modelLeadership model
Leadership modelPhil Steitz
Ā 
Open Development in the Enterprise
Open Development in the EnterpriseOpen Development in the Enterprise
Open Development in the EnterprisePhil Steitz
Ā 
Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCPPhil Steitz
Ā 
Principles of Technology Leadership
Principles of Technology LeadershipPrinciples of Technology Leadership
Principles of Technology LeadershipPhil Steitz
Ā 

More from Phil Steitz (7)

Programming Math in Java - Lessons from Apache Commons Math
Programming Math in Java - Lessons from Apache Commons MathProgramming Math in Java - Lessons from Apache Commons Math
Programming Math in Java - Lessons from Apache Commons Math
Ā 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
Ā 
Commons Nabla
Commons NablaCommons Nabla
Commons Nabla
Ā 
Leadership model
Leadership modelLeadership model
Leadership model
Ā 
Open Development in the Enterprise
Open Development in the EnterpriseOpen Development in the Enterprise
Open Development in the Enterprise
Ā 
Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCP
Ā 
Principles of Technology Leadership
Principles of Technology LeadershipPrinciples of Technology Leadership
Principles of Technology Leadership
Ā 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
Ā 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
Ā 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
Ā 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
Ā 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
Ā 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
Ā 
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024BookNet Canada
Ā 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
Ā 
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Alan Dix
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
Ā 
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Patryk Bandurski
Ā 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Ā 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Ā 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Ā 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
Ā 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Ā 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Ā 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
Ā 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Ā 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
Ā 
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
Ā 
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
Ā 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Ā 
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
Ā 
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Ā 

Concurrent Programming Techniques

  • 2. Agenda ā€¢ Motivational Examples ā€¢ Computing Model ā€¢ Race Conditions ā€¢ Deadlocks ā€¢ Resources 2
  • 3. Sleeping Barber ā€œBAUā€ Process Barber cuts hair When ļ¬nished, he checks the waiting room If no one is there, he goes to sleep in the chair Customers arriving while the barber is asleep wake the barber What can go wrong? Barber ļ¬nishes, walks to waiting room Customer arrives and goes to wake the barber They do not see each other, return and wait indeļ¬nitely 3
  • 4. Dining Philosophers ā€œBAUā€ Process Philosophers alternate between thinking and eating Two forks are required to eat spaghetti When ļ¬nished thinking, philosophers seek forks When ļ¬nished eating, philosophers put forks down What can go wrong? Process of picking up, putting down forks can result in each philosopher holding one fork - none can eat Dining Philosophers Demo http://www.doc.ic.ac.uk/~jnm/concurrency/classes/Diners/Diners.html 4
  • 5. Computing Canonical Model ā€¢ Processes spawn threads to do work ā€¢ Threads maintain local state but can also access shared state ā€¢ Threads can be active, suspended, blocked waiting for resources or sleeping ā€¢ Threads execute concurrently - truly concurrently in multi-processor environments, virtually concurrently in single- processor environments ā€¢ Thread scheduling is managed by the parent process, operating system and / or application ā€¢ Sequencing of operations across different threads is in general unpredictable Shared State 5
  • 6. Simple Computing Problem Bad Timing Web App Hit Counter ā€¢ Multi-threaded web app wants to maintain a count of the number of hits it gets Read counter ā€¢ Shared state is used to maintain the count ā€¢ Request processing threads update the count each time they process a request ā€¢ Under heavy load, the app seems to ā€œmissā€ Read counter some hits. Why? Assign counter+1 public void increment() { Assign counter+1 count = count + 1; } Badness results from B reading the counter while A is in process of updating it. This is an example of a race condition. 6
  • 7. Solution Semaphore Keep B out while A updates ā€¢ Could make ā€œcount++ā€ operation atomic (i.e. unable to be interrupted.) The JDK 1.5 AtomicInteger class does this. Close the door ā€¢ More general solution is to synchronize access to the shared resource ā€¢ Using a semaphore, Thread A signals exclusive access to the critical section of code that does the update Knock on door ā€¢ Simplest semaphore is a mutex (mutual exclusion - just one allowed in at a time) and simplest implementation Update, open door in Java is via the synchronized keyword Close door, update public synchronized void increment() { count = count + 1; } Note that the same solution would work for the sleeping barber (close door to waiting room) 7
  • 8. Synchronized Keyword in Java ā€¢ Acts as a mutex on blocks of code ā€¢ Can protect entire methods, or blocks within methods ā€¢ Uses the concept of a monitor on an object to represent the mutex - code entering a synchronized block acquires an object monitor ā€¢ When no object is speciļ¬ed, the monitor on the object executing the code is implied ā€¢ Synchronization locks are reentrant - i.e., if a thread owns an objectā€™s monitor and it enters another method that requires the same monitor, it is allowed in ā€¢ When a thread leaves a synchronized block, it releases the associated monitor (even if an exception occurs) Parent objectā€™s monitor Fuā€™s monitor public synchronized void foo() { public void foo() { public void foo() { fu.bar(); synchronized (this) { synchronized (fu) { } fu.bar(); fu.bar(); } } } } 8
  • 9. Concurrent Object Access Method Object Threads Object References When multiple threads share references to the same object, they can concurrently call the same method on the object, unless synchronization prevents this. A class is thread-safe if concurrently executing threads can safely hold references to instances of the class. 9
  • 10. Programmerā€™s Challenge: Situational Awareness ā€¢ The question always needs to be asked, ā€œwill multiple threads hold references to instances of this class at the same time?ā€ Unfortunately, it is sometimes hard to know. ā€¢ Most common use cases involving concurrent access are created by application containers, often in conjunction with application frameworks. Containers manage threads and frameworks instantiate objects. Fun begins when the Singleton Pattern is used by the framework. Primitive Survival Technique: Avoid the bad neighborhood altogether ā€¢ Keep is Stateless Stupid (KISS) - avoid maintaining state across method calls ā€¢ Prefer immutable objects - only ļ¬nal ļ¬elds, all set by constructors ā€¢ Never spawn threads - let the container manage them ā€¢ Use tested, thread-safe resource providers (e.g. databases) to maintain state (when you are dragged kicking and screaming into acknowledging the need to maintain state at all) ā€¢ Encapsulate parameters needed by methods in value objects and pass these to/from methods instead of relying on instance ļ¬elds 10
  • 11. Anatomical Example public class Foo { public static final int HOSIERY_THRESHOLD = 1000; No worries private boolean fubar; ... public void hose(int ways) { Careful! int newWays = generateNewWays(); if (ways + newWays > HOSIERY_THRESHOLD) { fubar = true; } } ā€¢ Static ļ¬nal ļ¬elds are initialized when the class is loaded and donā€™t change thereafter, so all threads see the same values - threadsafe ā€¢ Method parameters are provided to each thread on the call stack and are only visible to that thread for the duration of the method - threadsafe ā€¢ Local variables declared within methods are only visible to the thread activating the method for the duration of the method - threadsafe ā€¢ Class member ļ¬elds are visible to all threads, so if two threads can be inside a method that uses a member ļ¬eld at the same time, care must be taken to synchronize access 11
  • 12. Example - Struts 1.x Actions Servlet Container 1. When the web app starts, it loads ActionServlet the Struts ActionServlet (one ActionServlet instance per web FooAction application - a singleton) BarAction 2. When the ActionServlet is initialized, it reads its conļ¬guration and loads one instance each of the Action classes deļ¬ned in its conļ¬guration FubarAction (more singletons) 3. When browser requests arrive, the container assigns processing threads to requests and passes requests mapped to the Struts application to the Struts ActionServlet instance 4. The Struts ActionServlet calls perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) on the single Action instance that it uses for all requests Consequence: Struts Action classes must be threadsafe! rtfm://struts.apache.org/1.0.2/userGuide/building_controller.html#action_classes 12
  • 13. Struts 1.x Example (Cont.) Inside a Struts Action Class: private String successPath = null; private String failedPath = null; private String maxAttemptsPath = null; public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set forward paths, using request information setForwardPaths(mapping, request ); ... Depending on processing outcome, forward to configured path } private void setForwardPaths(ActionMapping mapping, HttpServletRequest request) { ... successPath = ... failedPath = ... maxAttemptsPath = ... } Problem: If two requests for this action are processed concurrently, and the computed forward paths are different, control can be misdirected. 13
  • 14. Struts 1.x Example - Fix private String successPath = null; private String failedPath = null; private String maxAttemptsPath = null; public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set forward paths, using request information ForwardPaths forwardPaths = getForwardPaths(mapping,request); String successPath = forwardPaths.getSuccessPath(); String failedPath = forwardPaths.getFailedPath(); String maxAttemptsPath = forwardPaths.getMaxAttemptsPath(); ... Depending on processing outcome, forward to configured path } private ForwardPaths setForwardPaths(ActionMapping mapping, HttpServletRequest request) { // Compute and store local variables success, failed, maxAttempt representing paths ... return new ForwardPaths(success, failed, maxAttempts); } Eliminating the member ļ¬elds makes the class threadsafe. Introduction of a value object (ForwardPaths inner class not shown) enables data to be safely transmitted to/from the private helper method. 14
  • 15. Deadlock Thread 1 Thread 2 Acquire lock A Acquire lock B Block waiting to acquire lock B Block waiting to acquire lock A Thread 1 canā€™t proceed until it gets the lock that Thread 2 is holding on B. Thread 2 canā€™t proceed until it gets the lock that Thread 1 is holding on A. No other threads can do anything that requires either lock. This kind of situation can cause application servers to ā€œhang.ā€ 15
  • 16. DeadLock Example Apache Commons Pool provides Maintenance Thread Client Thread a generic object pooling API and implementations Apache Commons DBCP is a Acquire pool lock database connection pool that Acquire factory uses Commons Pool as its lock underlying object pool Block waiting to When used together, versions acquire factory 1.2-1.4 of Commons Pool and lock 1.1-1.2.x of Commons DBCP could create a deadlock (tracked Block waiting to as DBCP-44 in ASF JIRA) acquire pool lock Source of the deadlock: Contention between client threads borrowing / returning Resolution: Modify pool code to move all objects and a maintenance thread invocations of factory methods outside of for locks on the pool and objects synchronized scope (so lock in 0 is released before used by the poolā€™s object factory step 2 is attempted) 16
  • 17. Avoiding Deadlocks Rule number 0: Leave concurrency management to external resource providers or fully tested frameworks - try to design around the need for synchronization Rule number 1: When holding a lock, never call any methods that require other locks Would completely eliminate possibility of deadlock; but unfortunately not always possible Rule number 2: When you must use multiple locks to perform actions in your application, establish a hierarchy of locks and always acquire locks in the order determined by the hierarchy Rule number 3: Maintain a complete and consistent execution model of application subsystems and make explicit (via both documentation and test cases) invariants that enforce lock hierarchy and/or prevent contention for locks Rule number 4: Pay special attention to exception processing, especially when using explicit locks (i.e., objects that implement the Lock interface) - make sure locks are released on all execution paths 17
  • 18. Resources Java Threads, Scott Oaks, Henry Wong (http://oreilly.com/catalog/9780596007829/index.html? CMP=ILL-4GV796923290) The Little Book of Semaphores, Allen B Downey (http://greenteapress.com/semaphores/) ā€œConcurrent Programming with J2SE 1.5ā€ (http://java.sun.com/developer/technicalArticles/ J2SE/concurrency/) Also read carefully the class javadoc for all of the classes in the concurrency package ā€œHierarchical Ordering of Sequential Processesā€, Edsker Dijkstra, working paper (http:// userweb.cs.utexas.edu/users/EWD/ewd03xx/EWD310.PDF) ā€œSequential Programming vs Concurrent Programmingā€, Jerry Cain (http://academicearth.org/ lectures/sequential-programming-concurrent-programming) A little ā€œOTā€: ā€œOn the Nature of Time - Why does Nature Abhor Deadlocks?ā€, Christine Cordula Dantas (http://www.fqxi.org/data/essay-contest-ļ¬les/Dantas_Nattime2_1.pdf? phpMyAdmin=0c371ccdae9b5ff3071bae814fb4f9e9) 18