SlideShare a Scribd company logo
1 of 49
Allan Huang@Patentcloud.com
 A Process runs independently and isolated of other processes.
It cannot directly access shared data in other processes.
 A Thread is a so called Lightweight Process. It has its own call
stack, but can access shared data of other threads in the same
process. Every thread has its own memory cache – Thread
Local Storage.
 A Java application runs by default in One Process.
 Inter-process communication (IPC) is a mechanism that allows
the exchange of data between processes, e.g. Java
applications.
 If it behaves correctly when accessed from multiple threads,
regardless of the scheduling or interleaving of the execution
of those threads by the runtime environment, and with no
additional synchronization or other coordination on the part
of the calling code.
 Use proper locking mechanism when modifying shared data.
 Locking establishes the orderings needed to satisfy the Java
Memory Model (JSR-133) and guarantee the visibility of
changes to other threads.
 synchronized modifier
◦ A block of code that is marked as synchronized in Java tells the JVM: "only let
one thread in here at a time".
 final modifier
◦ Values of final fields, including objects inside collections referred to by
a final reference, can be safely read without synchronization.
◦ Store a reference to an object in a final field only makes
the reference immutable, not the actual object.
 volatile modifier
◦ It’s used to mark a field and indicate that changes to that field must be seen
by all subsequent reads by other threads, regardless of synchronization.
◦ It’s not suitable for cases where we want to Read-Update-Write as an atomic
operation.
◦ synchronization modifier supports mutual exclusion and visibility. In contrast,
the volatile modifier only supports visibility.
Object Level Locking Class Level Locking
 Compare-and-swap (CAS)
◦ A hardware instruction is much more Lightweight than Java's monitor-
based synchronization mechanism and is used to implement some
highly scalable concurrent classes.
 Atomic classes
◦ Support atomic compound actions on a single value in a lock-free
manner similar to volatile.
 Java Thread Local Storage - TLS
 It’s typically private static fields
in classes that wish to associate
state with a thread, e.g. a
current user or transaction.
 The best way to avoid memory
leak is to call remove() method
or set(null) on the ThreadLocal
instance once the job is done.
 Thread-per-task approach
◦ When a large number of threads may be created, each created thread
requires memory, and too many threads may exhaust the available
memory, forcing the application to terminate.
 Executor Framework
◦ Use a flexible Thread Pool implementation, in which a fixed or certain
number of threads would service incoming tasks.
 Executors factory methods
◦ newSingleThreadExecutor
◦ newFixedThreadPool
◦ newCachedThreadPool
◦ newSingleThreadScheduledExecutor
◦ newScheduledThreadPool
 Runnable, Callable and Future
◦ A Callable is like the familiar
Runnable but can return a result and
throw an exception.
◦ A Future is a marker representing a
result that will be available at some
point in the future.
Fixed Thread Pool Scheduled Thread Pool
 CopyOnWriteArrayList
 CopyOnWriteArraySet
◦ ConcurrentSkipListSet
 Iterator
◦ Uses a snapshot of the underlying list (or set) and does not reflect any
changes to the list or set after the snapshot was created.
◦ Never throw a ConcurrentModificationException.
◦ Doesn't support remove(), set(o) and add(o) methods, and throws
UnsupportedOperationException.
 Use cases
◦ Share the data structure among several threads and have few writes
and many reads.
 One of most common Java EE performance problems is infinite
looping triggered from the non-thread safe HashMap get()
and put() operations.
 Performance comparison
◦ Non-thread safe HashMap
◦ ConcurrentHashMap
 ConcurrentNavigableMap
 ConcurrentSkipListMap
◦ SynchronizedHashMap
◦ HashTable
 BlockingQueue
◦ Unidirectional
◦ ArrayBlockingQueue
◦ ConcurrentLinkedQueue
◦ DelayQueue
◦ LinkedBlockingQueue
◦ PriorityBlockingQueue
◦ PriorityQueue
◦ SynchronousQueue
 Deque
◦ Bidirectional
◦ ArrayDeque
◦ ConcurrentLinkedDeque
◦ LinkedBlockingDeque
Producer Consumer
 A Semaphore is capable of restricting thread access to a common
resource, or sending signals between threads to avoid missed
signals.
 It's often implemented as a protected variable whose value is
incremented by acquire(): -1 and decremented by release(): +1.
 Objective
◦ Guarding Critical Sections
◦ Sending Signals Between Threads
 Use cases
◦ Limiting concurrent access to disk
◦ Thread creation limiting
◦ JDBC connection pooling / limiting
◦ Network connection throttling
◦ Throttling CPU or memory intensive tasks
 A CountDownLatch causes one or more threads to wait for a
given set of operations to complete.
 The CountDownLatch is initialized with a count. Threads may
call await() to wait for the count to reach 0. Other threads may
call countDown(): -1 to reduce count.
 Not reusable once the count has reached 0.
 Use cases
◦ Achieving Maximum Parallelism
◦ Wait for several threads to complete
Semaphore Semaphore Cont.
CountDownLatch CountDownLatch cont.
 A CyclicBarrier lets a set of threads wait for
each other to reach a common barrier point.
 It can be reused indefinitely after the waiting
threads are released.
 Participants call await() and block until the
count is reached, at which point an optional
barrier task is executed by the last arriving
thread, and all threads are released.
 Use cases
◦ Multiplayer games that cannot start until the last
player has joined.
CyclicBarrier CyclicBarrier cont.
 An Exchanger (rendezvous) lets a pair of threads exchange
data items. An exchanger is similar to a cyclic barrier whose
count is set to 2 but also supports exchange of data when
both threads reach the exchange point.
 An Exchanger waits for threads to meet at the exchange()
method and swap values atomically.
 Use cases
◦ Genetic Algorithm, Pipeline Design
Exchanger Exchanger cont.
 A Phaser (introduced in Java 7) is similar to a CyclicBarrier in
that it lets a group of threads wait on a barrier and then
proceed after the last thread arrives.
 It’s similar in functionality to CyclicBarrier and
CountDownLatch but supporting more flexible usage.
 Unlike a cyclic barrier, which coordinates a fixed number of
threads, a Phaser can coordinate a variable number of threads,
which can register or deregister at any time.
Phaser Phaser cont.
 CountDownLatch
◦ Created with a fixed number of threads.
◦ Cannot be reset.
◦ Allows threads to wait or continue with its execution.
 CyclicBarrier
◦ Created with a fixed number of threads.
◦ Can be reset.
◦ The threads have to wait till all the threads arrive.
 Phaser
◦ Can register/add or deregister/remove threads dynamically.
◦ Can be reset.
◦ Allows threads to wait or continue with its execution.
◦ Supports multiple Phases.
 Lock
◦ Implemented by ReentrantLock.
◦ It provides all the features of synchronized keyword with additional
ways to create different Conditions for locking, providing timeout for
thread to wait for lock.
 ReadWriteLock
◦ Implemented by ReentrantReadWriteLock.
◦ It contains a pair of associated locks, Read Lock for read-only
operations and Write Lock for writing. The Read Lock may be held
simultaneously by multiple reader threads as long as there are no
writer threads. The Write Lock is exclusive.
 Lock
◦ Ability to lock interruptibly.
◦ Ability to timeout while waiting for lock.
◦ Power to create fair lock.
◦ API to get list of waiting thread for lock.
◦ Flexibility to try for lock without blocking.
 Synchronization
◦ Not required a try-finally block to release lock.
◦ Easy to read code.
ReentrantLock ReentrantLock cont.
Reader Writer
 Fork/Join Framework (introduced in Java 7)
◦ A style of parallel programming in which problems are solved by
(recursively) splitting them into subtasks that are solved in parallel.
- Professor Doug Lea
 The Fork/Join Framework is a special executor service for
running a special kind of task. It is designed to work well with
for divide-and-conquer, or recursive task-processing.
1. Separate (fork) each large task into smaller tasks.
2. Process each task in a separate thread (separating those into even
smaller tasks if necessary).
3. Join the results.
Fork/Join Pseudo Code Fork/Join Process
 ForkJoinPool
◦ An ExecutorService implementationthat runs ForkJoinTasks.
 ForkJoinWorkerThread
◦ A thread managed by a ForkJoinPool, which executes ForkJoinTasks.
 ForkJoinTask
◦ Describes thread-like entities that have a much lighter weight than
normal threads. Many tasks and subtasks can be hosted by very few
actual threads.
◦ RecursiveAction
 A recursive resultless ForkJoinTask.
◦ RecursiveTask
 A recursive result-bearing ForkJoinTask.
Fork/Join Fork/Join cont.
 Fork/Join allows you to easily execute divide-and-conquer
jobs, which have to be implemented manually if you want to
execute it in ExecutorService.
 In practice ExecutorService is usually used to process many
independent requests concurrently, and fork-join when you
want to accelerate one coherent job.
 Added Value of Task Parallelism in Batch Sweeps
 Java 7 util.concurrent API UML Class Diagram Examples
 Java performance tuning tips or everything you want to know
about Java performance in 15 minutes
 Thread synchronization, object level locking and class level
locking
 Java 7: HashMap vs ConcurrentHashMap
 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap – How
a HashMap can be Synchronized in Java
 Java concurrency: Understanding CopyOnWriteArrayList and
CopyOnWriteArraySet
 java.util.concurrent.Phaser Example
 Java Tip: When to use ForkJoinPool vs ExecutorService
 Java 101: Java concurrency without the pain, Part 1
 Java 101: Java concurrency without the pain, Part 2
 Book excerpt: Executing tasks in threads
 Modern threading for not-quite-beginners
 Modern threading: A Java concurrency primer
 Java concurrency (multi-threading) - Tutorial
 Understanding the Core Concurrency Concepts
 Java Concurrency / Multithreading Tutorial
 java.util.concurrent - Java Concurrency Utilities
 Java BlockingQueue Example implementing Producer Consumer
Problem
 Java Concurrency with ReadWriteLock
 Java Lock Example and Concurrency Lock vs synchronized
 Java ReentrantReadWriteLock Example
 ReentrantLock Example in Java, Difference between synchronized
vs ReentrantLock
Concurrency in  Java

More Related Content

What's hot (20)

Java IO
Java IOJava IO
Java IO
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Protocol Buffers
Protocol BuffersProtocol Buffers
Protocol Buffers
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 

Similar to Concurrency in Java

Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHarry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaYoung Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentCiklum
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 

Similar to Concurrency in Java (20)

Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Java-7 Concurrency
Java-7 ConcurrencyJava-7 Concurrency
Java-7 Concurrency
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Java tips
Java tipsJava tips
Java tips
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

More from Allan Huang

Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser ComparisonAllan Huang
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System DevelopmentAllan Huang
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureAllan Huang
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New EvolutionAllan Huang
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New EvolutionAllan Huang
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web DesignAllan Huang
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementAllan Huang
 
Build Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapBuild Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapAllan Huang
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 MultithreadingAllan Huang
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web ApplicationAllan Huang
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data StorageAllan Huang
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script PatternsAllan Huang
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommandAllan Huang
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site InitiationAllan Huang
 
Architecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEArchitecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEAllan Huang
 

More from Allan Huang (20)

Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Drools
DroolsDrools
Drools
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser Comparison
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered Architecture
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New Evolution
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And Improvement
 
YQL Case Study
YQL Case StudyYQL Case Study
YQL Case Study
 
Build Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGapBuild Cross-Platform Mobile Application with PhoneGap
Build Cross-Platform Mobile Application with PhoneGap
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web Application
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data Storage
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommand
 
Web Crawler
Web CrawlerWeb Crawler
Web Crawler
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site Initiation
 
Architecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EEArchitecture of eSobi club based on J2EE
Architecture of eSobi club based on J2EE
 

Recently uploaded

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Recently uploaded (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

Concurrency in Java

  • 2.  A Process runs independently and isolated of other processes. It cannot directly access shared data in other processes.  A Thread is a so called Lightweight Process. It has its own call stack, but can access shared data of other threads in the same process. Every thread has its own memory cache – Thread Local Storage.  A Java application runs by default in One Process.  Inter-process communication (IPC) is a mechanism that allows the exchange of data between processes, e.g. Java applications.
  • 3.  If it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.  Use proper locking mechanism when modifying shared data.  Locking establishes the orderings needed to satisfy the Java Memory Model (JSR-133) and guarantee the visibility of changes to other threads.
  • 4.  synchronized modifier ◦ A block of code that is marked as synchronized in Java tells the JVM: "only let one thread in here at a time".  final modifier ◦ Values of final fields, including objects inside collections referred to by a final reference, can be safely read without synchronization. ◦ Store a reference to an object in a final field only makes the reference immutable, not the actual object.  volatile modifier ◦ It’s used to mark a field and indicate that changes to that field must be seen by all subsequent reads by other threads, regardless of synchronization. ◦ It’s not suitable for cases where we want to Read-Update-Write as an atomic operation. ◦ synchronization modifier supports mutual exclusion and visibility. In contrast, the volatile modifier only supports visibility.
  • 5. Object Level Locking Class Level Locking
  • 6.  Compare-and-swap (CAS) ◦ A hardware instruction is much more Lightweight than Java's monitor- based synchronization mechanism and is used to implement some highly scalable concurrent classes.  Atomic classes ◦ Support atomic compound actions on a single value in a lock-free manner similar to volatile.
  • 7.  Java Thread Local Storage - TLS  It’s typically private static fields in classes that wish to associate state with a thread, e.g. a current user or transaction.  The best way to avoid memory leak is to call remove() method or set(null) on the ThreadLocal instance once the job is done.
  • 8.
  • 9.  Thread-per-task approach ◦ When a large number of threads may be created, each created thread requires memory, and too many threads may exhaust the available memory, forcing the application to terminate.  Executor Framework ◦ Use a flexible Thread Pool implementation, in which a fixed or certain number of threads would service incoming tasks.
  • 10.
  • 11.
  • 12.  Executors factory methods ◦ newSingleThreadExecutor ◦ newFixedThreadPool ◦ newCachedThreadPool ◦ newSingleThreadScheduledExecutor ◦ newScheduledThreadPool  Runnable, Callable and Future ◦ A Callable is like the familiar Runnable but can return a result and throw an exception. ◦ A Future is a marker representing a result that will be available at some point in the future.
  • 13. Fixed Thread Pool Scheduled Thread Pool
  • 14.
  • 15.  CopyOnWriteArrayList  CopyOnWriteArraySet ◦ ConcurrentSkipListSet  Iterator ◦ Uses a snapshot of the underlying list (or set) and does not reflect any changes to the list or set after the snapshot was created. ◦ Never throw a ConcurrentModificationException. ◦ Doesn't support remove(), set(o) and add(o) methods, and throws UnsupportedOperationException.  Use cases ◦ Share the data structure among several threads and have few writes and many reads.
  • 16.
  • 17.  One of most common Java EE performance problems is infinite looping triggered from the non-thread safe HashMap get() and put() operations.  Performance comparison ◦ Non-thread safe HashMap ◦ ConcurrentHashMap  ConcurrentNavigableMap  ConcurrentSkipListMap ◦ SynchronizedHashMap ◦ HashTable
  • 18.  BlockingQueue ◦ Unidirectional ◦ ArrayBlockingQueue ◦ ConcurrentLinkedQueue ◦ DelayQueue ◦ LinkedBlockingQueue ◦ PriorityBlockingQueue ◦ PriorityQueue ◦ SynchronousQueue
  • 19.  Deque ◦ Bidirectional ◦ ArrayDeque ◦ ConcurrentLinkedDeque ◦ LinkedBlockingDeque
  • 20.
  • 21.
  • 23.
  • 24.  A Semaphore is capable of restricting thread access to a common resource, or sending signals between threads to avoid missed signals.  It's often implemented as a protected variable whose value is incremented by acquire(): -1 and decremented by release(): +1.  Objective ◦ Guarding Critical Sections ◦ Sending Signals Between Threads  Use cases ◦ Limiting concurrent access to disk ◦ Thread creation limiting ◦ JDBC connection pooling / limiting ◦ Network connection throttling ◦ Throttling CPU or memory intensive tasks
  • 25.  A CountDownLatch causes one or more threads to wait for a given set of operations to complete.  The CountDownLatch is initialized with a count. Threads may call await() to wait for the count to reach 0. Other threads may call countDown(): -1 to reduce count.  Not reusable once the count has reached 0.  Use cases ◦ Achieving Maximum Parallelism ◦ Wait for several threads to complete
  • 28.  A CyclicBarrier lets a set of threads wait for each other to reach a common barrier point.  It can be reused indefinitely after the waiting threads are released.  Participants call await() and block until the count is reached, at which point an optional barrier task is executed by the last arriving thread, and all threads are released.  Use cases ◦ Multiplayer games that cannot start until the last player has joined.
  • 30.  An Exchanger (rendezvous) lets a pair of threads exchange data items. An exchanger is similar to a cyclic barrier whose count is set to 2 but also supports exchange of data when both threads reach the exchange point.  An Exchanger waits for threads to meet at the exchange() method and swap values atomically.  Use cases ◦ Genetic Algorithm, Pipeline Design
  • 32.  A Phaser (introduced in Java 7) is similar to a CyclicBarrier in that it lets a group of threads wait on a barrier and then proceed after the last thread arrives.  It’s similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.  Unlike a cyclic barrier, which coordinates a fixed number of threads, a Phaser can coordinate a variable number of threads, which can register or deregister at any time.
  • 34.  CountDownLatch ◦ Created with a fixed number of threads. ◦ Cannot be reset. ◦ Allows threads to wait or continue with its execution.  CyclicBarrier ◦ Created with a fixed number of threads. ◦ Can be reset. ◦ The threads have to wait till all the threads arrive.  Phaser ◦ Can register/add or deregister/remove threads dynamically. ◦ Can be reset. ◦ Allows threads to wait or continue with its execution. ◦ Supports multiple Phases.
  • 35.  Lock ◦ Implemented by ReentrantLock. ◦ It provides all the features of synchronized keyword with additional ways to create different Conditions for locking, providing timeout for thread to wait for lock.  ReadWriteLock ◦ Implemented by ReentrantReadWriteLock. ◦ It contains a pair of associated locks, Read Lock for read-only operations and Write Lock for writing. The Read Lock may be held simultaneously by multiple reader threads as long as there are no writer threads. The Write Lock is exclusive.
  • 36.  Lock ◦ Ability to lock interruptibly. ◦ Ability to timeout while waiting for lock. ◦ Power to create fair lock. ◦ API to get list of waiting thread for lock. ◦ Flexibility to try for lock without blocking.  Synchronization ◦ Not required a try-finally block to release lock. ◦ Easy to read code.
  • 38.
  • 40.  Fork/Join Framework (introduced in Java 7) ◦ A style of parallel programming in which problems are solved by (recursively) splitting them into subtasks that are solved in parallel. - Professor Doug Lea  The Fork/Join Framework is a special executor service for running a special kind of task. It is designed to work well with for divide-and-conquer, or recursive task-processing. 1. Separate (fork) each large task into smaller tasks. 2. Process each task in a separate thread (separating those into even smaller tasks if necessary). 3. Join the results.
  • 41. Fork/Join Pseudo Code Fork/Join Process
  • 42.  ForkJoinPool ◦ An ExecutorService implementationthat runs ForkJoinTasks.  ForkJoinWorkerThread ◦ A thread managed by a ForkJoinPool, which executes ForkJoinTasks.  ForkJoinTask ◦ Describes thread-like entities that have a much lighter weight than normal threads. Many tasks and subtasks can be hosted by very few actual threads. ◦ RecursiveAction  A recursive resultless ForkJoinTask. ◦ RecursiveTask  A recursive result-bearing ForkJoinTask.
  • 44.  Fork/Join allows you to easily execute divide-and-conquer jobs, which have to be implemented manually if you want to execute it in ExecutorService.  In practice ExecutorService is usually used to process many independent requests concurrently, and fork-join when you want to accelerate one coherent job.
  • 45.
  • 46.  Added Value of Task Parallelism in Batch Sweeps  Java 7 util.concurrent API UML Class Diagram Examples  Java performance tuning tips or everything you want to know about Java performance in 15 minutes  Thread synchronization, object level locking and class level locking  Java 7: HashMap vs ConcurrentHashMap  HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap – How a HashMap can be Synchronized in Java
  • 47.  Java concurrency: Understanding CopyOnWriteArrayList and CopyOnWriteArraySet  java.util.concurrent.Phaser Example  Java Tip: When to use ForkJoinPool vs ExecutorService  Java 101: Java concurrency without the pain, Part 1  Java 101: Java concurrency without the pain, Part 2  Book excerpt: Executing tasks in threads  Modern threading for not-quite-beginners  Modern threading: A Java concurrency primer
  • 48.  Java concurrency (multi-threading) - Tutorial  Understanding the Core Concurrency Concepts  Java Concurrency / Multithreading Tutorial  java.util.concurrent - Java Concurrency Utilities  Java BlockingQueue Example implementing Producer Consumer Problem  Java Concurrency with ReadWriteLock  Java Lock Example and Concurrency Lock vs synchronized  Java ReentrantReadWriteLock Example  ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock