SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton PatternMudasir Qazi
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton PatternBorey Lim
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSeerat Malik
 
Java - Singleton Pattern
Java - Singleton PatternJava - Singleton Pattern
Java - Singleton PatternCharles Casadei
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
Android async task
Android async taskAndroid async task
Android async taskMadhu Venkat
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
 

Tendances (12)

Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 
Thread&multithread
Thread&multithreadThread&multithread
Thread&multithread
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 
Java - Singleton Pattern
Java - Singleton PatternJava - Singleton Pattern
Java - Singleton Pattern
 
React hooks
React hooksReact hooks
React hooks
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
javathreads
javathreadsjavathreads
javathreads
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
Struts
StrutsStruts
Struts
 
Android async task
Android async taskAndroid async task
Android async task
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
 

Similaire à Java Tutorials - Concurrency

Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 

Similaire à Java Tutorials - Concurrency (20)

Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java
JavaJava
Java
 
multithreading
multithreadingmultithreading
multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java
JavaJava
Java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Java threading
Java threadingJava threading
Java threading
 
thread os.pptx
thread os.pptxthread os.pptx
thread os.pptx
 

Dernier

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Dernier (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

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