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

PPTX
C# Thread synchronization
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
PPTX
Architectural patterns part 3
PPTX
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
PPTX
Singleton Pattern (Sole Object with Global Access)
PDF
React hooks Episode #1: An introduction.
PPT
Android - Thread, Handler and AsyncTask
PPTX
The Singleton Pattern Presentation
C# Thread synchronization
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Architectural patterns part 3
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Singleton Pattern (Sole Object with Global Access)
React hooks Episode #1: An introduction.
Android - Thread, Handler and AsyncTask
The Singleton Pattern Presentation

What's hot (12)

PPTX
Design Pattern - Singleton Pattern
PPTX
Thread&multithread
PPTX
Singleton Pattern
PPTX
Singleton Design Pattern - Creation Pattern
PDF
Java - Singleton Pattern
PPTX
React hooks
PDF
Android development training programme , Day 3
PDF
javathreads
PPTX
Singleton Pattern
PPTX
PPTX
Android async task
PPTX
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Design Pattern - Singleton Pattern
Thread&multithread
Singleton Pattern
Singleton Design Pattern - Creation Pattern
Java - Singleton Pattern
React hooks
Android development training programme , Day 3
javathreads
Singleton Pattern
Android async task
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Ad

Similar to Java Tutorials - Concurrency (20)

PPTX
Threading.pptx
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PDF
Multithreading Introduction and Lifecyle of thread
PPTX
Multithreading in java
PPTX
Multithreading in java
PPT
PPT
multithreading
PPT
Multithreading
 
PPT
PPT
Java Multithreading
PPT
Java multithreading
PPTX
Multithreading in java
PPTX
Multi-threaded Programming in JAVA
PPTX
Multi threading
PPT
Programming - Java-Threads-and-Synchronization.ppt
PPT
Md09 multithreading
PPTX
Slide 7 Thread-1.pptx
DOCX
Threadnotes
PPTX
Multithreading
PPT
Java Performance, Threading and Concurrent Data Structures
Threading.pptx
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
Multithreading Introduction and Lifecyle of thread
Multithreading in java
Multithreading in java
multithreading
Multithreading
 
Java Multithreading
Java multithreading
Multithreading in java
Multi-threaded Programming in JAVA
Multi threading
Programming - Java-Threads-and-Synchronization.ppt
Md09 multithreading
Slide 7 Thread-1.pptx
Threadnotes
Multithreading
Java Performance, Threading and Concurrent Data Structures
Ad

Recently uploaded (20)

PPTX
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
PPTX
Patient Appointment Booking in Odoo with online payment
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
Cost to Outsource Software Development in 2025
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
iTop VPN Crack Latest Version Full Key 2025
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
Website Design Services for Small Businesses.pdf
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Complete Guide to Website Development in Malaysia for SMEs
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
PPTX
history of c programming in notes for students .pptx
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
Patient Appointment Booking in Odoo with online payment
Wondershare Filmora 15 Crack With Activation Key [2025
Computer Software and OS of computer science of grade 11.pptx
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Cost to Outsource Software Development in 2025
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
iTop VPN Crack Latest Version Full Key 2025
Weekly report ppt - harsh dattuprasad patel.pptx
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Website Design Services for Small Businesses.pdf
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Why Generative AI is the Future of Content, Code & Creativity?
Complete Guide to Website Development in Malaysia for SMEs
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
history of c programming in notes for students .pptx
Operating system designcfffgfgggggggvggggggggg
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps

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