Multi Threading Enhancements
Multi Threading Enhancements
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
77 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
8.1) ThreadGroup
8.2) ThreadLocal
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
78 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
ThreadGroup:
Based on the Functionality we can Group Threads into a Single Unit which is
Nothing but ThreadGroup i.e. ThreadGroup Represents a Set of Threads.
In Addition a ThreadGroup can Also contains Other SubThreadGroups.
t1 t2 t3 -------------tn
t5 t6 t7
SubThreadGroup
ThreadGroup
ThreadGroup Class Present in java.lang Package and it is the Direct Child Class of
Object.
ThreadGroup provides a Convenient Way to Perform Common Operation for all
Threads belongs to a Particular Group.
Eg:Stop All Consumer Threads.
Suspend All Producer Threads.
Constructors:
Note:
In Java Every Thread belongs to Some Group.
Every ThreadGroup is the Child Group of System Group either Directly OR
Indirectly. Hence SystemGroup Acts as Root for all ThreadGroup’s in Java.
System ThreadGroup Represents System Level Threads Like ReferenceHandler,
SignalDispatcher, Finalizer, AttachListener Etc.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
79 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
System
t 1 t2 t3
classThreadGroupDemo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getThreadGroup().getName());
System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());
ThreadGrouppg = new ThreadGroup("Parent Group");
System.out.println(pg.getParent().getName());
ThreadGroup cg = new ThreadGroup(pg, "Child Group"); main
System.out.println(cg.getParent().getName()); system
} main
} Parent Group
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
80 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
System
Main
Parent Group
Child Group
3) void setMaxPriority();
To Set Maximum Priority of ThreadGroup.
The Default Maximum Priority is 10.
Threads in the ThreadGroup that Already have Higher Priority, Not effected
but Newly Added Threads this MaxPriority is Applicable.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
81 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
classThreadGroupDemo {
public static void main(String[] args) {
ThreadGroup g1 = new ThreadGroup("tg");
Thread t1 = new Thread(g1, "Thread 1");
Thread t2 = new Thread(g1, "Thread 2");
g1.setMaxPriority(3);
Thread t3 = new Thread(g1, "Thread 3");
System.out.println(t1.getPriority()); 5
System.out.println(t2.getPriority()); 5
System.out.println(t3.getPriority()); 3
}
}
8) int enumerate(Thread[] t): To Copy All Active Threads of this Group into provided
Thread Array. In this Case SubThreadGroup Threads also will be Considered.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
82 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
10) booleanisDaemon():
2
1
java.lang.ThreadGroup[name=Parent Group,maxpri=10]
Thread[Child Thread 1,5,Parent Group]
Thread[Child Thread 2,5,Parent Group]
java.lang.ThreadGroup[name=Child Group,maxpri=10]
Child Thread
Child Thread
0
java.lang.ThreadGroup[name=Parent Group,maxpri=10]
java.lang.ThreadGroup[name=Child Group,maxpri=10]
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
83 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
classThreadGroupDemo {
public static void main(String[] args) {
ThreadGroup system = Thread.currentThread().getThreadGroup().getParent();
Thread[] t = new Thread[system.activeCount()];
system.enumerate(t);
for (Thread t1: t) {
System.out.println(t1.getName()+"-------"+t1.isDaemon());
}
} Reference Handler-------true
} Finalizer-------true
Signal Dispatcher-------true
Attach Listener-------true
main-------false
ThreadLocal:
Note:
☀ ThreadLocal Class introduced in 1.2 Version.
☀ ThreadLocal can be associated with Thread Scope.
☀ All the Code which is executed by the Thread has Access to Corresponding
ThreadLocal Variables.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
84 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
☀ A Thread can Access its Own Local Variables and can’t Access Other Threads
Local Variables.
☀ Once Thread Entered into Dead State All Local Variables are by Default Eligible for
Garbage Collection.
Methods:
1) Object get(); Returns the Value of ThreadLocal Variable associated with Current
Thread.
2) Object initialValue();
Returns the initialValue of ThreadLocal Variable of Current Thread.
The Default Implementation of initialValue() Returns null.
To Customize Our initialValue we have to Override initialValue().
4) void remove();
To Remove the Current Threads Local Variable Value.
After Remove if we are trying to Access it will be reinitialized Once Again by
invoking its initialValue().
This Method Newly Added in 1.5 Version.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
85 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
classThreadLocalDemo {
public static void main(String[] args) {
ThreadLocaltl = new ThreadLocal();
System.out.println(tl.get()); //null
tl.set("Durga");
System.out.println(tl.get()); //Durga
tl.remove();
System.out.println(tl.get()); //null
}
}
//Overriding of intialValue()
classThreadLocalDemo {
public static void main(String[] args) {
ThreadLocaltl = new ThreadLocal() {
protected Object initialValue() {
return "abc";
}
};
System.out.println(tl.get()); //abc
tl.set("Durga");
System.out.println(tl.get()); //Durga
tl.remove();
System.out.println(tl.get()); //abc
}
}
In the Above Program for Every Customer Thread a Separate customerID will be
maintained by ThreadLocal Object.
ThreadLocalVs Inheritance:
Parent Threads ThreadLocal Variables are by Default Not Available to the Child
Threads.
If we want to Make Parent Threads Local Variables Available to Child Threads we
should go for InheritableThreadLocal Class.
It is the Child Class of ThreadLocal Class.
By Default Child Thread Values are Same as Parent Thread Values but we can
Provide Customized Values for Child Threads by Overriding childValue().
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
88 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
Java.util.concurrent.locks package:
Lock(I):
A Lock Object is Similar to Implicit Lock acquired by a Thread to Execute
synchronized Method OR synchronized Block
Lock Implementations Provide More Extensive Operations than Traditional
Implicit Locks.
2) booleantryLock();
To Acquire the Lock if it is Available.
If the Lock is Available then Thread Acquires the Lock and Returns true.
If the Lock Unavailable then this Method Returns false and Continue its
Execution.
In this Case Thread is Never Blocked.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
89 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
if (l.tryLock()) {
Perform Safe Operations
}
else {
Perform Alternative Operations
}
4) void lockInterruptedly();
ReentrantLock
It implements Lock Interface and it is the Direct Child Class of an Object.
Reentrant Means a Thread can acquires Same Lock Multiple Times without any
Issue.
Internally ReentrantLock Increments Threads Personal Count whenever we Call
lock() and Decrements Counter whenever we Call unlock() and Lock will be
Released whenever Count Reaches ‘0’.
Constructors:
1) ReentrantLockrl = new ReentrantLock();
Creates an Instance of ReentrantLock.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
90 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
If Fairness is true then Longest Waiting Thread can acquired Lock Once it is
Avaiable i.e. if follows First - In First – Out.
If Fairness is false then we can’t give any Guarantee which Thread will get the
Lock Once it is Available.
Note: If we are Not specifying any Fairness Property then by Default it is Not Fair.
1) void lock();
2) booleantryLock();
4) void lockInterruptedly();
5) void unlock();
To Realease the Lock.
If the Current Thread is Not Owner of the Lock then we will get Runtime
Exception Saying IllegalMonitorStateException.
importjava.util.concurrent.locks.ReentrantLock;
class Test {
public static void main(String[] args) {
ReentrantLock l = new ReentrantLock();
l.lock();
l.lock();
System.out.println(l.isLocked()); //true
System.out.println(l.isHeldByCurrentThread()); //true
System.out.println(l.getQueueLength()); //0
l.unlock();
System.out.println(l.getHoldCount()); //1
System.out.println(l.isLocked()); //true
l.unlock();
System.out.println(l.isLocked()); //false
System.out.println(l.isFair()); //false
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
92 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
importjava.util.concurrent.locks.ReentrantLock;
class Display {
ReentrantLock l = new ReentrantLock(true);
public void wish(String name) {
l.lock(); 1
Good Morning
for(int i=0; i<5; i++) {
Dhoni
System.out.println("Good Morning");
Good Morning
try {
Dhoni
Thread.sleep(2000);
Good Morning
}
Dhoni
catch(InterruptedException e) {}
System.out.println(name); Good Morning
Dhoni
}
l.unlock(); 2 Good Morning
Dhoni
}
Good Morning
}
Yuva Raj
classMyThread extends Thread {
Good Morning
Display d;
Yuva Raj
String name;
Good Morning
MyThread(Display d, String name) {
Yuva Raj
this.d = d;
Good Morning
this.name = name;
Yuva Raj
}
Good Morning
public void run() {
Yuva Raj
d.wish(name);
Good Morning
}
ViratKohli
}
Good Morning
classReentrantLockDemo {
ViratKohli
public static void main(String[] args) {
Good Morning
Display d = new Display();
ViratKohli
MyThread t1 = new MyThread(d, "Dhoni");
Good Morning
MyThread t2 = new MyThread(d, "Yuva Raj");
ViratKohli
MyThread t3 = new MyThread(d, "ViratKohli");
Good Morning
t1.start();
t2.start(); ViratKohli
t3.start();
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
93 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
If we Comment Both Lines 1 and 2 then All Threads will be executed Simultaneously
and Hence we will get Irregular Output.
If we are Not Commenting then the Threads will be executed One by One and Hence we
will get Regular Output
importjava.util.concurrent.locks.ReentrantLock;
classMyThread extends Thread {
staticReentrantLock l = new ReentrantLock();
MyThread(String name) {
super(name);
}
public void run() {
if(l.tryLock()) {
SOP(Thread.currentThread().getName()+" Got Lock and Performing Safe Operations");
try {
Thread.sleep(2000);
}
catch(InterruptedException e) {}
l.unlock();
}
else {
System.out.println(Thread.currentThread().getName()+" Unable To Get Lock
and Hence Performing Alternative Operations");
}
}
}
classReentrantLockDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread("First Thread");
MyThread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
94 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
importjava.util.concurrent.TimeUnit;
importjava.util.concurrent.locks.ReentrantLock;
classMyThread extends Thread {
staticReentrantLock l = new ReentrantLock();
MyThread(String name) {
super(name);
}
public void run() {
do {
try {
if(l.tryLock(1000, TimeUnit.MILLISECONDS)) {
SOP(Thread.currentThread().getName()+"------- Got Lock");
Thread.sleep(5000);
l.unlock();
SOP(Thread.currentThread().getName()+"------- Releases Lock");
break;
}
else {
SOP(Thread.currentThread().getName()+"------- Unable To Get Lock And Will Try Again");
}
}
catch(InterruptedException e) {}
}
while(true);
}
}
classReentrantLockDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread("First Thread");
MyThread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
95 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
Thread Pools:
Creating a New Thread for Every Job May Create Performance and Memory
Problems.
To Overcome this we should go for Thread Pool Concept.
Thread Pool is a Pool of Already Created Threads Ready to do Our Job.
Java 1.5 Version Introduces Thread Pool Framework to Implement Thread Pools.
Thread Pool Framework is Also Known as Executor Framework.
We can Create a Thread Pool as follows
ExecutorService service = Executors.newFixedThreadPool(3);//Our Choice
We can Submit a Runnable Job by using submit().
service.submit(job);
We can ShutdownExecutiorService by using shutdown().
service.shutdown();
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
classPrintJob implements Runnable {
String name;
PrintJob(String name) {
this.name = name;
}
public void run() {
SOP(name+"....Job Started By Thread:" +Thread.currentThread().getName());
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {}
SOP(name+"....Job Completed By Thread:" +Thread.currentThread().getName());
}
}
class ExecutorDemo {
public static void main(String[] args) {
PrintJob[] jobs = {
newPrintJob("Durga"),
newPrintJob("Ravi"),
newPrintJob("Nagendra"),
newPrintJob("Pavan"),
newPrintJob("Bhaskar"),
newPrintJob("Varma")
};
ExecutorService service = Executors.newFixedThreadPool(3);
for (PrintJob job : jobs) {
service.submit(job);
}
service.shutdown();
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
96 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
Output
Durga....Job Started By Thread:pool-1-thread-1
Ravi....Job Started By Thread:pool-1-thread-2
Nagendra....Job Started By Thread:pool-1-thread-3
Ravi....Job Completed By Thread:pool-1-thread-2
Pavan....Job Started By Thread:pool-1-thread-2
Durga....Job Completed By Thread:pool-1-thread-1
Bhaskar....Job Started By Thread:pool-1-thread-1
Nagendra....Job Completed By Thread:pool-1-thread-3
Varma....Job Started By Thread:pool-1-thread-3
Pavan....Job Completed By Thread:pool-1-thread-2
Bhaskar....Job Completed By Thread:pool-1-thread-1
Varma....Job Completed By Thread:pool-1-thread-3
On the Above Program 3 Threads are Responsible to Execute 6 Jobs. So that a Single
Thread can be reused for Multiple Jobs.
Note: Usually we can Use ThreadPool Concept to Implement Servers (Web Servers And
Application Servers).
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
97 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
importjava.util.concurrent.Callable;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.Future;
FAQ’S
1) What Is Multi Tasking?
4) When Compared With C++ What Is The Advantage In Java With Respect To Multi
Threading?
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
99 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
14) After Starting A Thread If We Try To Restart The Same Thread Once Again What
Will Happen?
20) How To Get Priority From Thread And Set Priority To A Thread?
21) If We Are Trying To Set Priority Of Thread As 100, What Will Happen?
22) If 2 Threads Having Different Priority Then Which Thread Will Get Chance First
For Execution?
23) If 2 Threads Having Same Priority Then Which Thread Will Get Chance First For
Execution?
28) What Is synchronized Key Word? Explain Its Advantages And Disadvantages?
31) While A Thread Executing Any Synchronized Method On The Given Object Is It
Possible To Execute Remaining Synchronized Methods On The Same Object
Simultaneously By Other Thread?
37) Why wait(), notify(), notifyAll() Methods Are Defined In Object Instead Of Thread
Class?
39) If A Waiting Thread Gets Notification Then It Will Enter Into Which State?
43) Once A Thread Gives Notification Then Which Waiting Thread Will Get A Chance?
49) What Is Starvation And Explain Difference Between Deadlock and Starvation?
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
102 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
103 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com