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

More Related Content

What's hot (12)

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

Similar to Java Tutorials - Concurrency (20)

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

Recently uploaded (20)

PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Everything you need to know about pricing & licensing Microsoft 365 Copilot f...
Q-Advise
 
PDF
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Salesforce Experience Cloud Consultant.pdf
VALiNTRY360
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Simplify React app login with asgardeo-sdk
vaibhav289687
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Everything you need to know about pricing & licensing Microsoft 365 Copilot f...
Q-Advise
 
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Salesforce Experience Cloud Consultant.pdf
VALiNTRY360
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Simplify React app login with asgardeo-sdk
vaibhav289687
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
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