SlideShare a Scribd company logo
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.
Concurrency in  Java
 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.
Concurrency in  Java
Concurrency in  Java
 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
Concurrency in  Java
 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.
Concurrency in  Java
 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
Concurrency in  Java
Concurrency in  Java
Producer Consumer
Concurrency in  Java
 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.
Concurrency in  Java
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.
Concurrency in  Java
 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
Ad

More Related Content

What's hot (20)

Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Knoldus Inc.
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Java RMI
Java RMIJava RMI
Java RMI
Prajakta Nimje
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Java Threads
Java ThreadsJava Threads
Java Threads
M Vishnuvardhan Reddy
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
SakkaravarthiS1
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
atozknowledge .com
 

Similar to Concurrency in Java (20)

Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Luis Goldster
 
Java-7 Concurrency
Java-7 ConcurrencyJava-7 Concurrency
Java-7 Concurrency
Masudul Haque
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Java tips
Java tipsJava tips
Java tips
Viswanath Lekshmanan
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
Ciklum
 
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
 
Concurrency
ConcurrencyConcurrency
Concurrency
Ankur Maheshwari
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Scheidt & Bachmann
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Multi-Threading in Java power point presenetation
Multi-Threading in Java power point presenetationMulti-Threading in Java power point presenetation
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
Multithreading
MultithreadingMultithreading
Multithreading
Ravi Chythanya
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Luis Goldster
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
Ciklum
 
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 Processes
Isuru Perera
 
Multi-Threading in Java power point presenetation
Multi-Threading in Java power point presenetationMulti-Threading in Java power point presenetation
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
Ad

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
Allan Huang
 
Drools
DroolsDrools
Drools
Allan Huang
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser Comparison
Allan Huang
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
Allan Huang
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered Architecture
Allan Huang
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
Allan Huang
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New Evolution
Allan Huang
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
Allan Huang
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
Allan Huang
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And Improvement
Allan Huang
 
YQL Case Study
YQL Case StudyYQL Case Study
YQL Case Study
Allan 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 PhoneGap
Allan Huang
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
Allan Huang
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web Application
Allan Huang
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data Storage
Allan Huang
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommand
Allan Huang
 
Web Crawler
Web CrawlerWeb Crawler
Web Crawler
Allan Huang
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site Initiation
Allan 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 J2EE
Allan Huang
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
Allan Huang
 
Java JSON Parser Comparison
Java JSON Parser ComparisonJava JSON Parser Comparison
Java JSON Parser Comparison
Allan Huang
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
Allan Huang
 
eSobi Website Multilayered Architecture
eSobi Website Multilayered ArchitectureeSobi Website Multilayered Architecture
eSobi Website Multilayered Architecture
Allan Huang
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
Allan Huang
 
Tomcat New Evolution
Tomcat New EvolutionTomcat New Evolution
Tomcat New Evolution
Allan Huang
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
Allan Huang
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
Allan Huang
 
Boilerpipe Integration And Improvement
Boilerpipe Integration And ImprovementBoilerpipe Integration And Improvement
Boilerpipe Integration And Improvement
Allan 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 PhoneGap
Allan Huang
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
Allan Huang
 
HTML5 Offline Web Application
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web Application
Allan Huang
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data Storage
Allan Huang
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Weighted feed recommand
Weighted feed recommandWeighted feed recommand
Weighted feed recommand
Allan Huang
 
eSobi Site Initiation
eSobi Site InitiationeSobi Site Initiation
eSobi Site Initiation
Allan 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 J2EE
Allan Huang
 
Ad

Recently uploaded (20)

Driving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital AgeDriving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital Age
SatishKumar2651
 
Building Apps for Good The Ethics of App Development
Building Apps for Good The Ethics of App DevelopmentBuilding Apps for Good The Ethics of App Development
Building Apps for Good The Ethics of App Development
Net-Craft.com
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Navigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdfNavigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdf
Applitools
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Gojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service BusinessGojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service Business
XongoLab Technologies LLP
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Driving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital AgeDriving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital Age
SatishKumar2651
 
Building Apps for Good The Ethics of App Development
Building Apps for Good The Ethics of App DevelopmentBuilding Apps for Good The Ethics of App Development
Building Apps for Good The Ethics of App Development
Net-Craft.com
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Navigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdfNavigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdf
Applitools
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 

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.
  • 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.
  • 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
  • 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.
  • 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
  • 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.
  • 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.
  • 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
  翻译: