SlideShare a Scribd company logo
Efficient Java Multithreading – Using
Executors to do everything that you can
do with Threads!
- By Arun K. Mehra
Java Multithreading Using Executors Framework
Disclaimer
 This presentation does not cover the basics of Java Multithreading
 It’s focus is primarily on the Executors Framework
 It is used in the online video course on Udemy – “Efficient Java
Multithreading with Executors”
 It’s probably a bit boring as it contains a lot of text but no funny
images and no code listings 
 The matter in the slides is actually explained in the video course
(sample videos can be viewed on You-Tube or Udemy)
 Still strong? Let’s roll! 
About me!
 My name is Arun Kumar Mehra.
 Nearly 13 years in Software Industry architecting and
developing Enterprise applications
 Worked in diverse domains – Life Insurance, Investment
Banking and Telecommunications
 Mostly used Java/JEE technologies
 Diehard fan of Open Source especially, Java, Groovy,
OSGi and Eclipse RCP/RAP
Pre-requisites
Good knowledge of Java and basic knowledge of
multithreading required …
o Why multithreading
o Scenarios where multithreading is useful (and where it is not!)
o Difference between thread-of-execution and Thread class
o Various execution-thread states
o Thread class operations
o Etc.
Course Structure
Introduction
Creating and Running threads
Naming threads
Returning values from threads
Creating daemon threads
Checking threads for ‘life’
01
02
03
04
05
06
Terminating threads
Handling Uncaught Exceptions
Waiting for other threads to
terminate
Scheduling tasks
07
08
09
10
02. CREATING & RUNNING THREADS
Starting Threads – Basic Mechanism
 Thread class object
 Runnable interface implementation or ‘The Task’
 Invocation of start() method on the Thread object
To run a task in a separate thread-of-execution, three
things are required:
Creating Threads Using Threads API
Quite a few ways. Difference lies in:
 The mechanism using which:
o The Thread object is created
o The Task is created
 The way these two objects are brought together and made to
collaborate
Running Threads Using Executors API
Only one way!
 Create task definition class
 Provide task object to an Executor Service
Executors API Overview
Preferred way of running tasks...
 Uses thread-pools
 Allocates heavy-weight threads upfront
 Decouples task-submission from thread-creation-and-management
 Each thread in the pool executes multiple tasks one-by-one
 A tasks-queue holds the tasks
 Threads are stopped when the Executor Service is stopped
Important Classes/Interfaces
Some frequently referred classes/interfaces while using
Executors framework:
 Executor (I)
void execute (Runnable task);
Important Classes/Interfaces
Some frequently referred classes/interfaces while using
Executors framework:
 Executor (I)
 ExecutorService (I)
<T> Future<T> submit (Callable<T> task);
Future<?> submit (Runnable task);
void shutdown ( );
List<Runnable> shutdownNow ( );
boolean isShutdown ( );
…
Important Classes/Interfaces
Some frequently referred classes/interfaces while using
Executors framework:
 Executor (I)
 ExecutorService (I)
 Executors (C)
public static ExecutorService newFixedThreadPool (int nThreads);
public static ExecutorService newCachedThreadPool ( );
public static ExecutorService newSingleThreadExecutor ( );
public static ExecutorService newSingleThreadScheduledExecutor ( );
…
Important Classes/Interfaces
Some frequently referred classes/interfaces while using
Executors framework:
 Executor (I)
 ExecutorService (I)
 Executors (C)
 Future (I)
V get ( ) throws InterruptedException , ExecutionException;
boolean isDone ( );
…
Available Thread-Pools
Many types of thread-pools available out-of-the-box:
 Fixed Thread Pool
 Cached Thread Pool
 Single Thread Executor (technically not a ‘pool’)
 Scheduled Thread Pool
 Single Thread Scheduled Executor (technically not a ‘pool’)
03. NAMING THREADS
What’s In A Name?
 ‘Thread-0’, ‘Thread-1’, ‘Thread-2’ – not very helpful in identifying
the threads
 More useful names would be:
o Directory-Scanner-Thread
o Timer-Thread
o Cache-Invalidating-Thread
 Helps in identifying special threads while debugging multi-threaded
applications
Why would you want to name threads …
Naming Normal Threads
 From within the task – at ‘thread-running’ time
 At ‘thread-creation’ time
Java provides a couple of opportunities …
Naming Executor Threads
 From within the task - at ‘thread-running’ time. Similar to the
technique that was used for renaming normal threads.
 Specify the thread-naming strategy at ‘executor-creation’ time
Two ways …
Default Names of Executor Threads
“pool-N-thread-M”
Internal pool-sequence-no. in the
JVM. Incremented every time a new
executor-pool is created!
Internal thread-sequence-no. inside
an executor-pool. Incremented every
time a new thread is created!
04. RETURNING VALUES FROM THREADS
Returning Values Using Normal Threads
 No language level support in normal Threads but there is support
in Executors
 A few ways for normal threads – see code
CTM: Values are returned from Tasks and not Threads!
Returning Values Using Executors
 Use Callable<T> instead of Runnable
o Override method: public T call() throws Exception
 ExecutorService.submit(Callable c)
 Call to submit() returns a Future<T>
 Task result can be retrieved using “T Future.get()” method
Out-of-the-box support provided by Java …
Processing Tasks’ Results in Order of Completion
 CompletionService<V> (I)
 ExecutorCompletionService<V> (C)
Use the following …
Future<V> submit (Callable<V> task)
Future<V> submit (Runnable task, V result)
Future<V> take ( )
Future<V> poll ( )
05. DAEMON THREADS
Daemon Threads – What and Why?
 Killed by the JVM as soon as no user thread is running any longer
o Can be stopped normally too – just like normal threads
 ‘main’ thread is a ‘user’ thread – not ‘daemon’
 Any kind of logic as desired can be put in daemon threads. E.g.:
o Directory-watcher-thread
o Socket-reader-thread
o Long-calculation-thread
Background and/or service providing threads …
Creating ‘Daemon’ Threads
 void Thread.setDaemon(boolean on)
o Also used in Executors API
 For Executors, implement a ThreadFactory and manipulate the
thread there to make it ‘daemon’
Thread class provides a method …
06. CHECKING THREADS FOR ‘LIFE’
Checking Threads for ‘Life’ - Threads API
 Use the method: boolean Thread.isAlive()
 Will return true if:
o … the thread is still running
 Will return false in the following scenarios:
o If the thread has not been started yet i.e Thread.start() has not been called yet or;
o If the thread has terminated – irrespective of whether it has successfully finished
executing its task or not
A thread is live if it has started but not terminated yet!!!
Checking Threads for ‘Life’ – Executors API
 Actually we are interested in task completion!!!
 Use the method: boolean Future.isDone()
 Will return true if:
o … the task execution is completed - whether normally, or with exception or with
cancellation
 Will return false if:
o … the task execution has not been completed yet – in fact, it may not even have
started yet!
Are we really interested in a thread being live …???
This deck is part of the full-fledged video course on :
EFFICIENT JAVA MULTITHREADING
WITH
EXECUTORS
Visit: Course
07. TERMINATING THREADS
Terminating Normal Threads
 Terminating at non-blocked portions in the task:
o Using a method coded for this purpose in the task
o Using interrupts:
 void Thread.interrupt() – usually called by another thread on the thread-to-be-
interrupted
 static boolean Thread.interrupted() – to be called from inside the interrupted thread
 boolean Thread.isInterrupted() – to be called by another thread on the interrupted
thread
 Terminating at points in the task where the thread is
blocked:
o Using interrupts – same methods as above
There are a few ways …
Terminating Individual Executor Tasks
 Terminating at non-blocked portions in the task:
o Using a method coded for this purpose in the task
o Using interrupts:
 boolean Future.cancel(boolean mayInterruptIfRunning) – to be called by the class holding
the Future ref.
 static boolean Thread.interrupted() – to be called from inside the interrupted task
 boolean Future.isCancelled() – to be called on the Future outside the interrupted task
 Terminating at points in the task where the thread is
blocked:
o Using interrupts – same methods as above
There are a few ways …
Terminating All Executor Tasks in One-Shot
 Use: List<Runnable> ExecutorService.shutdownNow()
o Uses interrupts under the hood
o Returns a list of tasks that were awaiting execution yet
 Interrupting may terminate blocked as well as non-blocked tasks
 Tasks must be coded to properly handle the interrupts
 To await termination after shutting down, use:
o boolean ExecService.awaitTermination(long timeout, TimeUnit unit)
Uses the same concepts as discussed previously …
08. HANDLING UNCAUGHT EXCEPTIONS
Uncaught Exceptions in Threads
 Implement Thread.UncaughtExceptionHandler interface
o Only one method: void uncaughtException(Thread t, Throwable e)
 Three ways to use UncaughtExceptionHandler:
o Set as default handler for all the threads in the system
 static void Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
o Set different handlers for different threads
 void Thread.setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
o Use a combination of default-handler and thread-specific-handlers
Leaking Exceptions from threads cannot be caught
directly …
Uncaught Exceptions in Executors
 Implement Thread.UncaughtExceptionHandler interface
o Only one method: void uncaughtException(Thread t, Throwable e)
 Three ways to use UncaughtExceptionHandler:
o Set as default handler for all the threads in the system
 static void Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
o Set different handlers for different threads
 Implement a ThreadFactory and;
 Use void Thread.setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
o Use a combination of default-handler and thread-specific-handlers
Similar ways of handling like the normal threads …
09. WAITING FOR OTHER THREADS TO
COMPLETE
Waiting for Normal-Threads to Finish
 Previously discussed techniques:
o boolean Thread.isAlive()
 To be called multiple times till you get a ‘false’
 Wastage of CPU cycles
o wait() and notify() mechanism
 To be coded manually in the tasks by the programmer
 A little difficult to get right
 Third technique:
o void Thread.join()
 In-built mechanism – works just like wait() and notify()
 Easy to use
Suspend the current thread so that it continues only after some
other thread(s) have finished …
Waiting for Executor Tasks to Finish
 Use java.util.concurrent.CountDownLatch
 An object of CountDownLatch is shared by the waiting tasks and
the awaited tasks.
o Waiting-tasks call void await() on the latch
o Awaited-tasks call void countdown() on the latch after finishing their
executions
o When the count reaches zero, waiting tasks are released, thereby, bringing
them out of suspended state and enabling their execution again.
Suspend the current task so that it continues only after some
other task(s) have finished …
10. SCHEDULING TASKS
Scheduling Tasks using Threads-API
 java.util.Timer
o Spawns a thread for executing the tasks
o Also contains scheduling logic
 java.util.TimerTask
o Implements Runnable interface
o Represents the task
o Should be short-lived for repeated
executions
For all scheduling needs, Threads-API provides two classes …
void schedule(TimerTask task, Date time)
void schedule(TimerTask task, long delay)
void schedule(TimerTask task, Date firstTime, long period)
void schedule(TimerTask task, long delay, long period)
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
void scheduleAtFixedRate(TimerTask task, long delay, long period)
void cancel()
long scheduledExecutionTime()
boolean cancel()
The “java.util.Timer” Class
 Single task-execution-thread per Timer object
 Timer tasks should complete quickly
 Always call Timer.cancel() when application is shutting down;
otherwise it may cause memory leak
 Don’t schedule any more tasks on the Timer after cancelling it
 Timer class is thread-safe
 Timer class does not offer any real-time guarantees
Few things worth stressing upon about the Timer class …
One-Time Execution in Future - Threads-API
 Two Timer methods for scheduling one-time execution:
o void schedule(TimerTask task, Date time)
o void schedule(TimerTask task, long delay)
Use Timer and TimerTask classes …
Repeated Fixed-Delay Executions – Threads API
Timer and TimerTask only, are used …
 Two methods in Timer class:
o void schedule(TimerTask task, long delay, long period)
o void schedule(TimerTask task, Date firstTime, long period)
 Next execution is scheduled when the current one begins
 Each execution is schedule relative to the actual start time of the
previous one
 Start-times drift forward over long runs
o Hence, frequency of executions becomes lower than that specified
 Appropriate for activities that require ‘smoothness’ over short
periods of time e.g. blinking cursor, hourly chimes, etc.
Repeated Fixed-Rate Executions – Threads API
Timer and TimerTask only, are used …
 Two methods in Timer class:
o void scheduleAtFixedRate(TimerTask task, long delay, long period)
o void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
 Next execution is scheduled when the current one begins
 Each execution is schedule relative to the scheduled start time of
the first execution
 Start-times DO NOT drift forward over long runs
o Hence, frequency of executions remains constant
 Appropriate for activities that are sensitive to ‘absolute time’ and
accurate frequency of executions
Scheduling Tasks - Executors-API
 Available pools:
o Single-thread-scheduled-executor
o Scheduled-thread-pool
 Created using Executors (C)
 ScheduledExecutorService (I)
o Extends ExecutorService (I)
 ScheduledFuture (I). Extends:
o Future (I)
o Delayed (I)
Special thread-pool(s) provided by Executors for scheduling tasks …
ScheduledFuture<?> schedule(Runnable command, long delay,
TimeUnit unit)
<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
TimeUnit unit)
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay, long delay, TimeUnit unit)
ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay, long period, TimeUnit unit)
static ScheduledExecutorService newSingleThreadScheduledExecutor()
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
long getDelay(TimeUnit unit)
One Time Execution in Future – Executors API
ScheduledExecutorService is used …
 Two methods:
o ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
o ScheduledFuture<?> schedule(Callable<V> callable, long delay, TimeUnit unit)
 Executions can be scheduled using a single-thread-executor or
scheduled-thread-pool
 No need to extend TimerTask. Normal Runnables and Callables only
are needed!
Repeated Fixed-Delay Executions – Executors API
ScheduledExecutorService is used …
 Only one method:
o ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long
initialDelay, long delay, TimeUnit unit)
 Executions can be scheduled using a single-thread-executor or
scheduled-thread-pool
 Each execution is schedule relative to the termination-time of the
previous execution
o Start-times drift forward over long runs
o Hence, frequency of executions becomes lower than that specified
 Only Runnables can be scheduled – no Callables!
Repeated Fixed-Rate Executions – Executors API
ScheduledExecutorService is used …
 Only one method:
o ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long
initialDelay, long period, TimeUnit unit)
 Executions can be scheduled using a single-thread-executor or
scheduled-thread-pool
 Each execution is schedule relative to the scheduled start time of
the first execution
o Start-times DO NOT drift forward over long runs
o Hence, frequency of executions remains constant
 Only Runnables can be scheduled – no Callables!
THANK YOU !!!
This deck is part of the full-fledged video course on :
EFFICIENT JAVA MULTITHREADING
WITH
EXECUTORS
Visit: Course
Ad

More Related Content

What's hot (20)

Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Cheng Ta Yeh
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
Taemon Piya-Lumyong
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
Rohit Gupta
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Gradle - the Enterprise Automation Tool
Gradle  - the Enterprise Automation ToolGradle  - the Enterprise Automation Tool
Gradle - the Enterprise Automation Tool
Izzet Mustafaiev
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Ganesh kumar reddy
 

Viewers also liked (20)

Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Trung Nguyen
 
Networking in java
Networking in javaNetworking in java
Networking in java
shravan kumar upadhayay
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
pallavikhandekar212
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
java networking
 java networking java networking
java networking
Waheed Warraich
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Thomas Zimmermann
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
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
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
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
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Ad

Similar to Java Multithreading Using Executors Framework (20)

Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
Krystian Zybała
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Abhijit Gaikwad
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
Chris Adamson
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
Krystian Zybała
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
Chris Adamson
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Ad

Recently uploaded (20)

AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

Java Multithreading Using Executors Framework

  • 1. Efficient Java Multithreading – Using Executors to do everything that you can do with Threads! - By Arun K. Mehra
  • 3. Disclaimer  This presentation does not cover the basics of Java Multithreading  It’s focus is primarily on the Executors Framework  It is used in the online video course on Udemy – “Efficient Java Multithreading with Executors”  It’s probably a bit boring as it contains a lot of text but no funny images and no code listings   The matter in the slides is actually explained in the video course (sample videos can be viewed on You-Tube or Udemy)  Still strong? Let’s roll! 
  • 4. About me!  My name is Arun Kumar Mehra.  Nearly 13 years in Software Industry architecting and developing Enterprise applications  Worked in diverse domains – Life Insurance, Investment Banking and Telecommunications  Mostly used Java/JEE technologies  Diehard fan of Open Source especially, Java, Groovy, OSGi and Eclipse RCP/RAP
  • 5. Pre-requisites Good knowledge of Java and basic knowledge of multithreading required … o Why multithreading o Scenarios where multithreading is useful (and where it is not!) o Difference between thread-of-execution and Thread class o Various execution-thread states o Thread class operations o Etc.
  • 6. Course Structure Introduction Creating and Running threads Naming threads Returning values from threads Creating daemon threads Checking threads for ‘life’ 01 02 03 04 05 06 Terminating threads Handling Uncaught Exceptions Waiting for other threads to terminate Scheduling tasks 07 08 09 10
  • 7. 02. CREATING & RUNNING THREADS
  • 8. Starting Threads – Basic Mechanism  Thread class object  Runnable interface implementation or ‘The Task’  Invocation of start() method on the Thread object To run a task in a separate thread-of-execution, three things are required:
  • 9. Creating Threads Using Threads API Quite a few ways. Difference lies in:  The mechanism using which: o The Thread object is created o The Task is created  The way these two objects are brought together and made to collaborate
  • 10. Running Threads Using Executors API Only one way!  Create task definition class  Provide task object to an Executor Service
  • 11. Executors API Overview Preferred way of running tasks...  Uses thread-pools  Allocates heavy-weight threads upfront  Decouples task-submission from thread-creation-and-management  Each thread in the pool executes multiple tasks one-by-one  A tasks-queue holds the tasks  Threads are stopped when the Executor Service is stopped
  • 12. Important Classes/Interfaces Some frequently referred classes/interfaces while using Executors framework:  Executor (I) void execute (Runnable task);
  • 13. Important Classes/Interfaces Some frequently referred classes/interfaces while using Executors framework:  Executor (I)  ExecutorService (I) <T> Future<T> submit (Callable<T> task); Future<?> submit (Runnable task); void shutdown ( ); List<Runnable> shutdownNow ( ); boolean isShutdown ( ); …
  • 14. Important Classes/Interfaces Some frequently referred classes/interfaces while using Executors framework:  Executor (I)  ExecutorService (I)  Executors (C) public static ExecutorService newFixedThreadPool (int nThreads); public static ExecutorService newCachedThreadPool ( ); public static ExecutorService newSingleThreadExecutor ( ); public static ExecutorService newSingleThreadScheduledExecutor ( ); …
  • 15. Important Classes/Interfaces Some frequently referred classes/interfaces while using Executors framework:  Executor (I)  ExecutorService (I)  Executors (C)  Future (I) V get ( ) throws InterruptedException , ExecutionException; boolean isDone ( ); …
  • 16. Available Thread-Pools Many types of thread-pools available out-of-the-box:  Fixed Thread Pool  Cached Thread Pool  Single Thread Executor (technically not a ‘pool’)  Scheduled Thread Pool  Single Thread Scheduled Executor (technically not a ‘pool’)
  • 18. What’s In A Name?  ‘Thread-0’, ‘Thread-1’, ‘Thread-2’ – not very helpful in identifying the threads  More useful names would be: o Directory-Scanner-Thread o Timer-Thread o Cache-Invalidating-Thread  Helps in identifying special threads while debugging multi-threaded applications Why would you want to name threads …
  • 19. Naming Normal Threads  From within the task – at ‘thread-running’ time  At ‘thread-creation’ time Java provides a couple of opportunities …
  • 20. Naming Executor Threads  From within the task - at ‘thread-running’ time. Similar to the technique that was used for renaming normal threads.  Specify the thread-naming strategy at ‘executor-creation’ time Two ways …
  • 21. Default Names of Executor Threads “pool-N-thread-M” Internal pool-sequence-no. in the JVM. Incremented every time a new executor-pool is created! Internal thread-sequence-no. inside an executor-pool. Incremented every time a new thread is created!
  • 22. 04. RETURNING VALUES FROM THREADS
  • 23. Returning Values Using Normal Threads  No language level support in normal Threads but there is support in Executors  A few ways for normal threads – see code CTM: Values are returned from Tasks and not Threads!
  • 24. Returning Values Using Executors  Use Callable<T> instead of Runnable o Override method: public T call() throws Exception  ExecutorService.submit(Callable c)  Call to submit() returns a Future<T>  Task result can be retrieved using “T Future.get()” method Out-of-the-box support provided by Java …
  • 25. Processing Tasks’ Results in Order of Completion  CompletionService<V> (I)  ExecutorCompletionService<V> (C) Use the following … Future<V> submit (Callable<V> task) Future<V> submit (Runnable task, V result) Future<V> take ( ) Future<V> poll ( )
  • 27. Daemon Threads – What and Why?  Killed by the JVM as soon as no user thread is running any longer o Can be stopped normally too – just like normal threads  ‘main’ thread is a ‘user’ thread – not ‘daemon’  Any kind of logic as desired can be put in daemon threads. E.g.: o Directory-watcher-thread o Socket-reader-thread o Long-calculation-thread Background and/or service providing threads …
  • 28. Creating ‘Daemon’ Threads  void Thread.setDaemon(boolean on) o Also used in Executors API  For Executors, implement a ThreadFactory and manipulate the thread there to make it ‘daemon’ Thread class provides a method …
  • 29. 06. CHECKING THREADS FOR ‘LIFE’
  • 30. Checking Threads for ‘Life’ - Threads API  Use the method: boolean Thread.isAlive()  Will return true if: o … the thread is still running  Will return false in the following scenarios: o If the thread has not been started yet i.e Thread.start() has not been called yet or; o If the thread has terminated – irrespective of whether it has successfully finished executing its task or not A thread is live if it has started but not terminated yet!!!
  • 31. Checking Threads for ‘Life’ – Executors API  Actually we are interested in task completion!!!  Use the method: boolean Future.isDone()  Will return true if: o … the task execution is completed - whether normally, or with exception or with cancellation  Will return false if: o … the task execution has not been completed yet – in fact, it may not even have started yet! Are we really interested in a thread being live …???
  • 32. This deck is part of the full-fledged video course on : EFFICIENT JAVA MULTITHREADING WITH EXECUTORS Visit: Course
  • 34. Terminating Normal Threads  Terminating at non-blocked portions in the task: o Using a method coded for this purpose in the task o Using interrupts:  void Thread.interrupt() – usually called by another thread on the thread-to-be- interrupted  static boolean Thread.interrupted() – to be called from inside the interrupted thread  boolean Thread.isInterrupted() – to be called by another thread on the interrupted thread  Terminating at points in the task where the thread is blocked: o Using interrupts – same methods as above There are a few ways …
  • 35. Terminating Individual Executor Tasks  Terminating at non-blocked portions in the task: o Using a method coded for this purpose in the task o Using interrupts:  boolean Future.cancel(boolean mayInterruptIfRunning) – to be called by the class holding the Future ref.  static boolean Thread.interrupted() – to be called from inside the interrupted task  boolean Future.isCancelled() – to be called on the Future outside the interrupted task  Terminating at points in the task where the thread is blocked: o Using interrupts – same methods as above There are a few ways …
  • 36. Terminating All Executor Tasks in One-Shot  Use: List<Runnable> ExecutorService.shutdownNow() o Uses interrupts under the hood o Returns a list of tasks that were awaiting execution yet  Interrupting may terminate blocked as well as non-blocked tasks  Tasks must be coded to properly handle the interrupts  To await termination after shutting down, use: o boolean ExecService.awaitTermination(long timeout, TimeUnit unit) Uses the same concepts as discussed previously …
  • 37. 08. HANDLING UNCAUGHT EXCEPTIONS
  • 38. Uncaught Exceptions in Threads  Implement Thread.UncaughtExceptionHandler interface o Only one method: void uncaughtException(Thread t, Throwable e)  Three ways to use UncaughtExceptionHandler: o Set as default handler for all the threads in the system  static void Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) o Set different handlers for different threads  void Thread.setUncaughtExceptionHandler(UncaughtExceptionHandler eh) o Use a combination of default-handler and thread-specific-handlers Leaking Exceptions from threads cannot be caught directly …
  • 39. Uncaught Exceptions in Executors  Implement Thread.UncaughtExceptionHandler interface o Only one method: void uncaughtException(Thread t, Throwable e)  Three ways to use UncaughtExceptionHandler: o Set as default handler for all the threads in the system  static void Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) o Set different handlers for different threads  Implement a ThreadFactory and;  Use void Thread.setUncaughtExceptionHandler(UncaughtExceptionHandler eh) o Use a combination of default-handler and thread-specific-handlers Similar ways of handling like the normal threads …
  • 40. 09. WAITING FOR OTHER THREADS TO COMPLETE
  • 41. Waiting for Normal-Threads to Finish  Previously discussed techniques: o boolean Thread.isAlive()  To be called multiple times till you get a ‘false’  Wastage of CPU cycles o wait() and notify() mechanism  To be coded manually in the tasks by the programmer  A little difficult to get right  Third technique: o void Thread.join()  In-built mechanism – works just like wait() and notify()  Easy to use Suspend the current thread so that it continues only after some other thread(s) have finished …
  • 42. Waiting for Executor Tasks to Finish  Use java.util.concurrent.CountDownLatch  An object of CountDownLatch is shared by the waiting tasks and the awaited tasks. o Waiting-tasks call void await() on the latch o Awaited-tasks call void countdown() on the latch after finishing their executions o When the count reaches zero, waiting tasks are released, thereby, bringing them out of suspended state and enabling their execution again. Suspend the current task so that it continues only after some other task(s) have finished …
  • 44. Scheduling Tasks using Threads-API  java.util.Timer o Spawns a thread for executing the tasks o Also contains scheduling logic  java.util.TimerTask o Implements Runnable interface o Represents the task o Should be short-lived for repeated executions For all scheduling needs, Threads-API provides two classes … void schedule(TimerTask task, Date time) void schedule(TimerTask task, long delay) void schedule(TimerTask task, Date firstTime, long period) void schedule(TimerTask task, long delay, long period) void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) void scheduleAtFixedRate(TimerTask task, long delay, long period) void cancel() long scheduledExecutionTime() boolean cancel()
  • 45. The “java.util.Timer” Class  Single task-execution-thread per Timer object  Timer tasks should complete quickly  Always call Timer.cancel() when application is shutting down; otherwise it may cause memory leak  Don’t schedule any more tasks on the Timer after cancelling it  Timer class is thread-safe  Timer class does not offer any real-time guarantees Few things worth stressing upon about the Timer class …
  • 46. One-Time Execution in Future - Threads-API  Two Timer methods for scheduling one-time execution: o void schedule(TimerTask task, Date time) o void schedule(TimerTask task, long delay) Use Timer and TimerTask classes …
  • 47. Repeated Fixed-Delay Executions – Threads API Timer and TimerTask only, are used …  Two methods in Timer class: o void schedule(TimerTask task, long delay, long period) o void schedule(TimerTask task, Date firstTime, long period)  Next execution is scheduled when the current one begins  Each execution is schedule relative to the actual start time of the previous one  Start-times drift forward over long runs o Hence, frequency of executions becomes lower than that specified  Appropriate for activities that require ‘smoothness’ over short periods of time e.g. blinking cursor, hourly chimes, etc.
  • 48. Repeated Fixed-Rate Executions – Threads API Timer and TimerTask only, are used …  Two methods in Timer class: o void scheduleAtFixedRate(TimerTask task, long delay, long period) o void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)  Next execution is scheduled when the current one begins  Each execution is schedule relative to the scheduled start time of the first execution  Start-times DO NOT drift forward over long runs o Hence, frequency of executions remains constant  Appropriate for activities that are sensitive to ‘absolute time’ and accurate frequency of executions
  • 49. Scheduling Tasks - Executors-API  Available pools: o Single-thread-scheduled-executor o Scheduled-thread-pool  Created using Executors (C)  ScheduledExecutorService (I) o Extends ExecutorService (I)  ScheduledFuture (I). Extends: o Future (I) o Delayed (I) Special thread-pool(s) provided by Executors for scheduling tasks … ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) static ScheduledExecutorService newSingleThreadScheduledExecutor() static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) long getDelay(TimeUnit unit)
  • 50. One Time Execution in Future – Executors API ScheduledExecutorService is used …  Two methods: o ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) o ScheduledFuture<?> schedule(Callable<V> callable, long delay, TimeUnit unit)  Executions can be scheduled using a single-thread-executor or scheduled-thread-pool  No need to extend TimerTask. Normal Runnables and Callables only are needed!
  • 51. Repeated Fixed-Delay Executions – Executors API ScheduledExecutorService is used …  Only one method: o ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)  Executions can be scheduled using a single-thread-executor or scheduled-thread-pool  Each execution is schedule relative to the termination-time of the previous execution o Start-times drift forward over long runs o Hence, frequency of executions becomes lower than that specified  Only Runnables can be scheduled – no Callables!
  • 52. Repeated Fixed-Rate Executions – Executors API ScheduledExecutorService is used …  Only one method: o ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)  Executions can be scheduled using a single-thread-executor or scheduled-thread-pool  Each execution is schedule relative to the scheduled start time of the first execution o Start-times DO NOT drift forward over long runs o Hence, frequency of executions remains constant  Only Runnables can be scheduled – no Callables!
  • 54. This deck is part of the full-fledged video course on : EFFICIENT JAVA MULTITHREADING WITH EXECUTORS Visit: Course