SlideShare a Scribd company logo
1 of 25
Thread
Join method
 The join method in java is provided by the java.lang.Thread class that
permits one thread to wait until the other thread to finish its execution.
 Similar to the sleep method in java, the join method is also dependent on the
operating system for the timing, so we should not assume that the join
method waits equal to the time we mention in the parameters.
 When the join method is invoked, the current thread stops its execution and
the thread goes into the wait state. The current remains in the wait state
until the thread on which the join method is invoked has achieved its dead
state. If interruption of the thread occurs, then it throws the
InterrptedException.
Naming Thread and Current Thread
 The Thread class provides methods to changes and get the name of a thread.
By default, each thread has a name i.e. thread-0, thread-1 and so on. By we
can change the name of the thread by using the setName method.
Priority of a Thread
 Each thread has a priority. Priorities are represented by a number between 1
and 10. in most cases, the thread scheduler schedules the threads according
to their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses. Not
that not only JVM a java programmer can also assign the priorities of a thread
explicitly in a java program.
Continued…
 getProirity: the java.lang.Thread.getPriority method returns the priority of
the given thread.
 setPriority: the java.lang.Thread.setPriority method updates or assign the
priority of the thread to newPriority. The method throws
IllegalArgumentExcpetion if the value newPriority goes out of the range,
which is 1 (minimum) to (maximum).
Continued…
 3 constants defined in Thread class:
 Public static int MIN_PRIORITY
 Public static in NORM_PRIORITY
 Public static int MAX_PROIRITY
 If there are two threads that have the same priority, then one can not predict
which thread will get the chance to execute first. The execution then is
dependent on the thread scheduler’s algorithm(FCFS, Round-Robin, etc).
Daemon Thread in java
 Daemon thread in java is a service provider thread that provides services to
the user thread. Its life depend on the mercy of user threads i.e. when all the
user threads dies, JVM terminates this thread automatically.
 There are many java daemon threads running automatically e.g. gc.
Points to remember for Daemon Thread
is java
 It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
Methods
 Public void setDaemon(Boolean status): is used to mark the current thread as
daemon thread or user thread.
 Public Boolean isDaemon(): is used to check that the current is daemon.
 Note: if you want to make a user thread as Daemon, it must not started
otherwise it will throw IllegaleThreadException
Thread Pool
 Thread Pool represents a group of worker threads that are waiting for the job
and reused many times.
 In the case of a thread pool a group of fixed threads is created. A thread from
the thread pool pulled out and assigned a job by the service provider. After
completion of the job, the thread is contained in the thread pool again.
Methods
 newFixedThreadPool(int s): the method creates a thread pool of the fixed
size.
 newCachedThreadPool(): the method creates a new thread pool that creates
the new threads when needed but will still use the previously created thread
whenever they are available to use.
 newSingleThreadExecutor(): the method creates a new thread.
Advantage of Java Thread Pool
 Better performance: it saves time because there is no need to create a new
thread.
Risks involved in Thread Pools
 Deadlock: it is a knows fact that deadlock can come in any program that
involves multithreading, and a thread pool introduces another scenario of
deadlock. Consider a scenario where all the threads that a re executing are
waiting for the results from the threads that are blocked and waiting in the
queue because of the non-availability of threads for the execution.
 Thread Leakage: leakage of threads occurs when a thread is being removed
from the pool to execute a task but is not returning to it after the completion
of the task. For example, when a thread throws the exception and the pool
class is not able to catch this exception, then the thread exits and reduces
the thread pool size by 1. if the same thing repeats a number of times, then
there are fair chances that the pool will become empty, and hence, there are
not threads available in the pool for executing other requests.
Continued…
 Resource Thrashing: a lot of time is wasted in context switching among
threads when the size of the thread pool is very large. Whenever there are
more threads than the optimal number may cause the starvation problem,
and it leads to resource thrashing.
Points to Remember
 Do not queue the tasks that are concurrently waiting for the results obtained
from the other tasks. It may lead to a deadlock situation.
 Care must be taken whenever threads are used for the operation that is long-
lived. It may result in the waiting of thread forever and will finally lead to the
leakage of the resource.
 In the end, the thread pool has to be ended explicitly. If it does not happen,
then the program continues to execute, and it never ends. Invoke the
shutdown() method on the thread pool to terminate the executor. Not that is
someone tries to send another task to the executor after shutdown, it will
throw a RejectedExecutionException.
Continued…
 To reduce the probability of running JVM out of memory, one can control the
maximum threads that can run in JVM. The thread pool cannot create new
threads after it has reached the maximum limit.
 A thread pool can use the same used thread if the thread has finished its
execution. Thus, the time and resources used for the creation of a new
thread are saved.
Thread Group
 Java provides a convenient way to group multiple threads in a single object.
In such a way, we can suspend, resume or interrupt a group of threads by a
single method call.
 Note: now suspend, resume and stop methods a re deprecated.
 Java thread group is implemented by java.lang.ThreadGroup class.
 A ThreadGroup represents a set of threads. A thread group can also include
the other thread group. The thread group creates a tree in which every
thread group except the initial thread group has a parent.
 A thread is allowed to access information about its own thread group, but it
cannot access the information about its thread group’s parent thread group or
any other thread groups.
Constructors
Methods
Continued…
Shutdown Hook
 A special construct that facilitates the developers to add some code that has
to be run when the Java Virtual Machine is shutting down is known as the Java
shutdown hook.
When does the JVM shut down?
 When:
 User presses ctrl+c on the command prompt
 System.exit(int) method is invoked
 User logoff
 User shutdown etc…
Continued…
 The addShutDownHook() method of the Runtime class is used to register the
thread with the Virtual Machine.
 The removeShutdownHook method of the Runtime class is invoked to remove
the registration of the already registered shutdown hooks.
Points to Remember
 No guarantee for the execution of the shutdown hooks.
 Before completion the shutdown hooks can be stopped forcefully. It is a
special case. Whenever a shutdown hooks start to execute one can forcefully
terminate it by shutting down the system. In this case, the operating system
for a specific amount of time. If the job is not done in that frame of time,
then the system has no choice than to forcefully terminate the running hooks.
 There can be more than one shutdown hooks. But there execution order is not
guaranteed.
 Within shutdown hooks it is not allowed to unregister or register the shutdown
hooks. If one tires to do so, the IllegalStateException is thrown by the JVM.
 The Runtime.halt() can stop the shutdown sequence that has been started.
Question?

More Related Content

Similar to Slide 7 Thread-1.pptx

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 

Similar to Slide 7 Thread-1.pptx (20)

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Java threading
Java threadingJava threading
Java threading
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java tips
Java tipsJava tips
Java tips
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Lecture 20
Lecture 20Lecture 20
Lecture 20
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Recently uploaded

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 

Recently uploaded (20)

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 

Slide 7 Thread-1.pptx

  • 2. Join method  The join method in java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish its execution.  Similar to the sleep method in java, the join method is also dependent on the operating system for the timing, so we should not assume that the join method waits equal to the time we mention in the parameters.  When the join method is invoked, the current thread stops its execution and the thread goes into the wait state. The current remains in the wait state until the thread on which the join method is invoked has achieved its dead state. If interruption of the thread occurs, then it throws the InterrptedException.
  • 3. Naming Thread and Current Thread  The Thread class provides methods to changes and get the name of a thread. By default, each thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName method.
  • 4. Priority of a Thread  Each thread has a priority. Priorities are represented by a number between 1 and 10. in most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Not that not only JVM a java programmer can also assign the priorities of a thread explicitly in a java program.
  • 5. Continued…  getProirity: the java.lang.Thread.getPriority method returns the priority of the given thread.  setPriority: the java.lang.Thread.setPriority method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentExcpetion if the value newPriority goes out of the range, which is 1 (minimum) to (maximum).
  • 6. Continued…  3 constants defined in Thread class:  Public static int MIN_PRIORITY  Public static in NORM_PRIORITY  Public static int MAX_PROIRITY  If there are two threads that have the same priority, then one can not predict which thread will get the chance to execute first. The execution then is dependent on the thread scheduler’s algorithm(FCFS, Round-Robin, etc).
  • 7. Daemon Thread in java  Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.  There are many java daemon threads running automatically e.g. gc.
  • 8. Points to remember for Daemon Thread is java  It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.  Its life depends on user threads.  It is a low priority thread.
  • 9. Methods  Public void setDaemon(Boolean status): is used to mark the current thread as daemon thread or user thread.  Public Boolean isDaemon(): is used to check that the current is daemon.  Note: if you want to make a user thread as Daemon, it must not started otherwise it will throw IllegaleThreadException
  • 10. Thread Pool  Thread Pool represents a group of worker threads that are waiting for the job and reused many times.  In the case of a thread pool a group of fixed threads is created. A thread from the thread pool pulled out and assigned a job by the service provider. After completion of the job, the thread is contained in the thread pool again.
  • 11. Methods  newFixedThreadPool(int s): the method creates a thread pool of the fixed size.  newCachedThreadPool(): the method creates a new thread pool that creates the new threads when needed but will still use the previously created thread whenever they are available to use.  newSingleThreadExecutor(): the method creates a new thread.
  • 12. Advantage of Java Thread Pool  Better performance: it saves time because there is no need to create a new thread.
  • 13. Risks involved in Thread Pools  Deadlock: it is a knows fact that deadlock can come in any program that involves multithreading, and a thread pool introduces another scenario of deadlock. Consider a scenario where all the threads that a re executing are waiting for the results from the threads that are blocked and waiting in the queue because of the non-availability of threads for the execution.  Thread Leakage: leakage of threads occurs when a thread is being removed from the pool to execute a task but is not returning to it after the completion of the task. For example, when a thread throws the exception and the pool class is not able to catch this exception, then the thread exits and reduces the thread pool size by 1. if the same thing repeats a number of times, then there are fair chances that the pool will become empty, and hence, there are not threads available in the pool for executing other requests.
  • 14. Continued…  Resource Thrashing: a lot of time is wasted in context switching among threads when the size of the thread pool is very large. Whenever there are more threads than the optimal number may cause the starvation problem, and it leads to resource thrashing.
  • 15. Points to Remember  Do not queue the tasks that are concurrently waiting for the results obtained from the other tasks. It may lead to a deadlock situation.  Care must be taken whenever threads are used for the operation that is long- lived. It may result in the waiting of thread forever and will finally lead to the leakage of the resource.  In the end, the thread pool has to be ended explicitly. If it does not happen, then the program continues to execute, and it never ends. Invoke the shutdown() method on the thread pool to terminate the executor. Not that is someone tries to send another task to the executor after shutdown, it will throw a RejectedExecutionException.
  • 16. Continued…  To reduce the probability of running JVM out of memory, one can control the maximum threads that can run in JVM. The thread pool cannot create new threads after it has reached the maximum limit.  A thread pool can use the same used thread if the thread has finished its execution. Thus, the time and resources used for the creation of a new thread are saved.
  • 17. Thread Group  Java provides a convenient way to group multiple threads in a single object. In such a way, we can suspend, resume or interrupt a group of threads by a single method call.  Note: now suspend, resume and stop methods a re deprecated.  Java thread group is implemented by java.lang.ThreadGroup class.  A ThreadGroup represents a set of threads. A thread group can also include the other thread group. The thread group creates a tree in which every thread group except the initial thread group has a parent.  A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group’s parent thread group or any other thread groups.
  • 21. Shutdown Hook  A special construct that facilitates the developers to add some code that has to be run when the Java Virtual Machine is shutting down is known as the Java shutdown hook.
  • 22. When does the JVM shut down?  When:  User presses ctrl+c on the command prompt  System.exit(int) method is invoked  User logoff  User shutdown etc…
  • 23. Continued…  The addShutDownHook() method of the Runtime class is used to register the thread with the Virtual Machine.  The removeShutdownHook method of the Runtime class is invoked to remove the registration of the already registered shutdown hooks.
  • 24. Points to Remember  No guarantee for the execution of the shutdown hooks.  Before completion the shutdown hooks can be stopped forcefully. It is a special case. Whenever a shutdown hooks start to execute one can forcefully terminate it by shutting down the system. In this case, the operating system for a specific amount of time. If the job is not done in that frame of time, then the system has no choice than to forcefully terminate the running hooks.  There can be more than one shutdown hooks. But there execution order is not guaranteed.  Within shutdown hooks it is not allowed to unregister or register the shutdown hooks. If one tires to do so, the IllegalStateException is thrown by the JVM.  The Runtime.halt() can stop the shutdown sequence that has been started.