SlideShare a Scribd company logo
Java Tutorials - Concurrency
Process - self-contained execution environment
Thread - lightweight processes, shares process’
memory and open files
Main Thread - creates the additional threads
Defining and Starting a Thread - Provide a Runnable object
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Defining and Starting a Thread - Subclass Thread
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Thread
sleep() - Causes the current thread to suspend execution for a specified period
t.join() - causes the current thread to pause execution until t's thread terminates
Thread Errors
Thread Interference - happens when two operations (consisting of multiple
steps), running in different threads, but acting on the same data, and the
sequences of steps overlap.
Memory consistency errors - different threads have inconsistent views of what
should be the same data
Synchronization helps prevents thread errors
Liveness and Liveness Problems
Liveness - A concurrent application's ability to execute in a timely manner
Problems:
Deadlock - a situation where two or more threads are blocked forever, waiting for each other
Starvation - a thread is unable to gain regular access to shared resources and is unable to make
progress. Shared resources are made unavailable for long periods by "greedy" threads.
Livelock - threads are not blocked - they are simply too busy responding to each other to resume work.
Example: two people walking towards each other in a corridor, when one person goes to the left, the other
goes to the right, and vice-versa
Immutable Objects
- state cannot change after it is constructed
- Maximum reliance on immutable objects is widely accepted as a sound
strategy for creating simple, reliable code.
- cannot be corrupted by thread interference or observed in an inconsistent
state.
Strategy for Defining Immutable Objects
1. Don’t provide setter methods
2. Make all fields final and private
3. Don’t allow subclasses to override methods
- Declare class as final
- Make constructor private, construct instances in factory methods
4. Don’t allow instance fields to be changed
- Don’t provide methods that modify the mutable objects
- Don’t share references to mutable objects. Never store references to external, mutable objects passed to the
constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal
mutable objects when necessary to avoid returning the originals in your methods.
High Level Concurrency Objects
Lock Objects
Executors - separate thread management from the rest of the application
Concurrent Collections
Atomic Variables
ThreadLocalRandom
java.util.concurrent Executor Interfaces
Executor - supports launching new tasks, executes submitted Runnable tasks
ExecutorService - extends Executor, manages termination, produces Futures for
tracking progress of asynchronous tasks
ScheduledExecutorService - schedule commands after a delay, or periodically
Thread Pools - Consists of Worker Threads
- Using worker threads minimizes the overhead due to thread creation
Fixed Thread Pools
- always has a specified number of threads running
- if a thread is terminated while it is still in use, it is automatically replaced
with a new thread
- Degrades gracefully: the application will not be servicing requests as quickly
as they come in, but it will be servicing them as quickly as the system can
sustain
Fork/Join Framework
- ExecutorService implementation that helps take advantage of multiple
processors
- designed for work that can be broken into smaller pieces recursively
- The goal is to use all the available processing power to enhance the
performance of the application
- distributes tasks to worker threads in a thread pool
- uses a work-stealing algorithm: Worker threads that run out of things to do
can steal tasks from other threads that are still busy
- Uses ForkJoinPool class to execute ForkJoinTask processes
Fork/Join Pseudocode
if (my portion of the work is small enough)
do the work directly
else
split my work into two pieces
invoke the two pieces and wait for the results
Concurrent Collections java.util.concurrent
Interfaces, atomic, synchronization unneeded, helps avoid memory consistency
errors
BlockingQueue
ConcurrentMap - ConcurrentHashMap (HashMap analog)
ConcurrentNavigableMap - ConcurrentSkipListMap (TreeMap analog)
Atomic Variables java.util.concurrent.atomic
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
java.util.concurrent.ThreadLocalRandom
- random number generator isolated to the current thread
- As contrasted to the global java.util.Random
- ThreadLocalRandom.current().nextX(...)
- Consider instead using SecureRandom in security-sensitive applications
Ad

Recommended

C# Thread synchronization
C# Thread synchronization
Prem Kumar Badri
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
 
Architectural patterns part 3
Architectural patterns part 3
assinha
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.
ManojSatishKumar
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
The Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Thread&multithread
Thread&multithread
PhD Research Scholar
 
Singleton Pattern
Singleton Pattern
Borey Lim
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
Seerat Malik
 
Java - Singleton Pattern
Java - Singleton Pattern
Charles Casadei
 
React hooks
React hooks
Sadhna Rana
 
Android development training programme , Day 3
Android development training programme , Day 3
DHIRAJ PRAVIN
 
javathreads
javathreads
Arjun Shanka
 
Singleton Pattern
Singleton Pattern
Reber Novanta
 
Struts
Struts
Ishita Gandhi
 
Android async task
Android async task
Madhu Venkat
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Sachintha Gunasena
 
Concurrency in Java
Concurrency in Java
Lakshmi Narasimhan
 
Concurrent Programming in Java
Concurrent Programming in Java
Lakshmi Narasimhan
 
Concurrency in Java
Concurrency in Java
Allan Huang
 
Multithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
Concurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Multi Threading
Multi Threading
Ferdin Joe John Joseph PhD
 
Java concurrency in practice
Java concurrency in practice
Deon Huang
 
Modern Java Concurrency
Modern Java Concurrency
Ben Evans
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 

More Related Content

What's hot (12)

Design Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Thread&multithread
Thread&multithread
PhD Research Scholar
 
Singleton Pattern
Singleton Pattern
Borey Lim
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
Seerat Malik
 
Java - Singleton Pattern
Java - Singleton Pattern
Charles Casadei
 
React hooks
React hooks
Sadhna Rana
 
Android development training programme , Day 3
Android development training programme , Day 3
DHIRAJ PRAVIN
 
javathreads
javathreads
Arjun Shanka
 
Singleton Pattern
Singleton Pattern
Reber Novanta
 
Struts
Struts
Ishita Gandhi
 
Android async task
Android async task
Madhu Venkat
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Sachintha Gunasena
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Singleton Pattern
Singleton Pattern
Borey Lim
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
Seerat Malik
 
Java - Singleton Pattern
Java - Singleton Pattern
Charles Casadei
 
Android development training programme , Day 3
Android development training programme , Day 3
DHIRAJ PRAVIN
 
Android async task
Android async task
Madhu Venkat
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Sachintha Gunasena
 

Similar to Java Tutorials - Concurrency (20)

Concurrency in Java
Concurrency in Java
Lakshmi Narasimhan
 
Concurrent Programming in Java
Concurrent Programming in Java
Lakshmi Narasimhan
 
Concurrency in Java
Concurrency in Java
Allan Huang
 
Multithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
Concurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Multi Threading
Multi Threading
Ferdin Joe John Joseph PhD
 
Java concurrency in practice
Java concurrency in practice
Deon Huang
 
Modern Java Concurrency
Modern Java Concurrency
Ben Evans
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Anand Narayanan
 
Concurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with java
Luis Goldster
 
Concurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with java
Fraboni Ec
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
Concurrent Programming in Java
Concurrent Programming in Java
Lakshmi Narasimhan
 
Concurrency in Java
Concurrency in Java
Allan Huang
 
Multithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
Concurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Java concurrency in practice
Java concurrency in practice
Deon Huang
 
Modern Java Concurrency
Modern Java Concurrency
Ben Evans
 
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Anand Narayanan
 
Concurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with java
Luis Goldster
 
Concurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with java
Fraboni Ec
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
Ad

Recently uploaded (20)

Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Ad

Java Tutorials - Concurrency

  • 1. Java Tutorials - Concurrency Process - self-contained execution environment Thread - lightweight processes, shares process’ memory and open files Main Thread - creates the additional threads
  • 2. Defining and Starting a Thread - Provide a Runnable object public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } }
  • 3. Defining and Starting a Thread - Subclass Thread public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
  • 4. Thread sleep() - Causes the current thread to suspend execution for a specified period t.join() - causes the current thread to pause execution until t's thread terminates
  • 5. Thread Errors Thread Interference - happens when two operations (consisting of multiple steps), running in different threads, but acting on the same data, and the sequences of steps overlap. Memory consistency errors - different threads have inconsistent views of what should be the same data Synchronization helps prevents thread errors
  • 6. Liveness and Liveness Problems Liveness - A concurrent application's ability to execute in a timely manner Problems: Deadlock - a situation where two or more threads are blocked forever, waiting for each other Starvation - a thread is unable to gain regular access to shared resources and is unable to make progress. Shared resources are made unavailable for long periods by "greedy" threads. Livelock - threads are not blocked - they are simply too busy responding to each other to resume work. Example: two people walking towards each other in a corridor, when one person goes to the left, the other goes to the right, and vice-versa
  • 7. Immutable Objects - state cannot change after it is constructed - Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. - cannot be corrupted by thread interference or observed in an inconsistent state.
  • 8. Strategy for Defining Immutable Objects 1. Don’t provide setter methods 2. Make all fields final and private 3. Don’t allow subclasses to override methods - Declare class as final - Make constructor private, construct instances in factory methods 4. Don’t allow instance fields to be changed - Don’t provide methods that modify the mutable objects - Don’t share references to mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
  • 9. High Level Concurrency Objects Lock Objects Executors - separate thread management from the rest of the application Concurrent Collections Atomic Variables ThreadLocalRandom
  • 10. java.util.concurrent Executor Interfaces Executor - supports launching new tasks, executes submitted Runnable tasks ExecutorService - extends Executor, manages termination, produces Futures for tracking progress of asynchronous tasks ScheduledExecutorService - schedule commands after a delay, or periodically
  • 11. Thread Pools - Consists of Worker Threads - Using worker threads minimizes the overhead due to thread creation Fixed Thread Pools - always has a specified number of threads running - if a thread is terminated while it is still in use, it is automatically replaced with a new thread - Degrades gracefully: the application will not be servicing requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain
  • 12. Fork/Join Framework - ExecutorService implementation that helps take advantage of multiple processors - designed for work that can be broken into smaller pieces recursively - The goal is to use all the available processing power to enhance the performance of the application - distributes tasks to worker threads in a thread pool - uses a work-stealing algorithm: Worker threads that run out of things to do can steal tasks from other threads that are still busy - Uses ForkJoinPool class to execute ForkJoinTask processes
  • 13. Fork/Join Pseudocode if (my portion of the work is small enough) do the work directly else split my work into two pieces invoke the two pieces and wait for the results
  • 14. Concurrent Collections java.util.concurrent Interfaces, atomic, synchronization unneeded, helps avoid memory consistency errors BlockingQueue ConcurrentMap - ConcurrentHashMap (HashMap analog) ConcurrentNavigableMap - ConcurrentSkipListMap (TreeMap analog)
  • 15. Atomic Variables java.util.concurrent.atomic import java.util.concurrent.atomic.AtomicInteger; class AtomicCounter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.incrementAndGet(); } public void decrement() { c.decrementAndGet(); } public int value() { return c.get(); } }
  • 16. java.util.concurrent.ThreadLocalRandom - random number generator isolated to the current thread - As contrasted to the global java.util.Random - ThreadLocalRandom.current().nextX(...) - Consider instead using SecureRandom in security-sensitive applications