SlideShare a Scribd company logo
Efficient Java Multithreading – Using
Executors to do everything that you can
do with Threads!
- By Arun K. Mehra
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

More Related Content

What's hot

Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scripting
VIKAS TIWARI
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
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
Monika Mishra
 
Program control statements in c#
Program control statements in c#Program control statements in c#
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cyclemyrajendra
 
Abstract class
Abstract classAbstract class
Abstract class
Tony Nguyen
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Net framework
Net frameworkNet framework
Net framework
Saiteja Kaparthi
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
Milan Thapa
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java Collections
Java  Collections Java  Collections
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Template pattern
Template patternTemplate pattern
Template pattern
Vithushan Vinayagamoorthy
 

What's hot (20)

Wrapper class
Wrapper classWrapper class
Wrapper class
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scripting
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Program control statements in c#
Program control statements in c#Program control statements in c#
Program control statements in c#
 
OOP java
OOP javaOOP java
OOP java
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Abstract class
Abstract classAbstract class
Abstract class
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Net framework
Net frameworkNet framework
Net framework
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Template pattern
Template patternTemplate pattern
Template pattern
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 

Viewers also liked

Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu 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
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
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 ProgrammingMousmi 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 StepGuo Albert
 

Viewers also liked (20)

Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
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
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
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
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
java networking
 java networking java networking
java networking
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
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
 

Similar to Java Multithreading Using Executors Framework

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
 
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
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
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
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
02-Basic-Java-Syntax.pdf
02-Basic-Java-Syntax.pdf02-Basic-Java-Syntax.pdf
02-Basic-Java-Syntax.pdf
erusmala888
 
Unit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptxUnit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptx
DrYogeshDeshmukh1
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 

Similar to Java Multithreading Using Executors Framework (20)

Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
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
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
 
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
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
java threads
java threadsjava threads
java threads
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
02-Basic-Java-Syntax.pdf
02-Basic-Java-Syntax.pdf02-Basic-Java-Syntax.pdf
02-Basic-Java-Syntax.pdf
 
Unit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptxUnit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptx
 
4759826-Java-Thread
4759826-Java-Thread4759826-Java-Thread
4759826-Java-Thread
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Java Multithreading Using Executors Framework

  • 1. Efficient Java Multithreading – Using Executors to do everything that you can do with Threads! - By Arun K. Mehra
  • 2.
  • 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