8.multi Threading Enhancements
8.multi Threading Enhancements
8.1) ThreadGroup
8.2) ThreadLocal
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
77 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
78 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
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. System
t1 t2 t3 -------------tn
t 1 t2 t3
SubThreadGroup
ThreadGroup
Main Child Child SubThreadGroup
ThreadGroup Class Present in java.lang Package and it is the Direct Child Class of Thread Thread 1 Thread 2
Object. Class
ThreadGroup provides a Convenient Way to Perform Common Operation for all
Threads belongs to a Particular Group.
Thread 1 Thread 2 Thread 3
Eg:Stop All Consumer Threads.
Suspend All Producer Threads.
Constructors:
Note:
In Java Every Thread belongs to Some Group. classThreadGroupDemo {
Every ThreadGroup is the Child Group of System Group either Directly OR public static void main(String[] args) {
System.out.println(Thread.currentThread().getThreadGroup().getName());
Indirectly. Hence SystemGroup Acts as Root for all ThreadGroup’s in Java.
System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());
System ThreadGroup Represents System Level Threads Like ReferenceHandler,
ThreadGrouppg = new ThreadGroup("Parent Group");
SignalDispatcher, Finalizer, AttachListener Etc.
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 nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
79 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
80 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR JAVA Means DURGASIR
classThreadGroupDemo {
public static void main(String[] args) {
System
ThreadGroup g1 = new ThreadGroup("tg");
Thread t1 = new Thread(g1, "Thread 1");
Thread t2 = new Thread(g1, "Thread 2");
Main
g1.setMaxPriority(3);
Thread t3 = new Thread(g1, "Thread 3");
System.out.println(t1.getPriority()); 5
Parent Group System.out.println(t2.getPriority()); 5
System.out.println(t3.getPriority()); 3
}
Child Group }
3) void setMaxPriority(); 6) intactiveCount(): Returns Number of Active Threads Present in the ThreadGroup.
To Set Maximum Priority of ThreadGroup.
The Default Maximum Priority is 10. 7) intactiveGroupCount(): It Returns Number of Active ThreadGroups Present in the
Threads in the ThreadGroup that Already have Higher Priority, Not effected Current ThreadGroup.
but Newly Added Threads this MaxPriority is Applicable.
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 nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
81 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
82 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
10) booleanisDaemon(): Write a Program to Display All Thread Names belongs to System Group
☀ A Thread can Access its Own Local Variables and can’t Access Other Threads
Local Variables. classThreadLocalDemo {
☀ Once Thread Entered into Dead State All Local Variables are by Default Eligible for public static void main(String[] args) {
Garbage Collection. ThreadLocaltl = new ThreadLocal();
System.out.println(tl.get()); //null
Constructor:ThreadLocaltl = new ThreadLocal(); tl.set("Durga");
Creates a ThreadLocal Variable. 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";
Methods:
}
1) Object get(); Returns the Value of ThreadLocal Variable associated with Current
};
Thread.
System.out.println(tl.get()); //abc
tl.set("Durga");
2) Object initialValue();
System.out.println(tl.get()); //Durga
Returns the initialValue of ThreadLocal Variable of Current Thread. tl.remove();
The Default Implementation of initialValue() Returns null. System.out.println(tl.get()); //abc
To Customize Our initialValue we have to Override initialValue(). }
}
3) void set(Object newValue);To Set a New Value.
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.
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().
if (l.tryLock()) {
Perform Safe Operations
Java.util.concurrent.locks package: }
else {
Perform Alternative Operations
Problems with Traditional synchronized Key Word }
If a Thread Releases the Lock then which waiting Thread will get that Lock we are
Not having any Control on this.
We can’t Specify Maximum waiting Time for a Thread to get Lock so that it will
Wait until getting Lock, which May Effect Performance of the System and Causes
Dead Lock.
3) boolentryLock(long time, TimeUnit unit);
We are Not having any Flexibility to Try for Lock without waiting.
To Acquire the Lock if it is Available.
There is No API to List All Waiting Threads for a Lock.
If the Lock is Unavailable then Thread can Wait until specified Amount of Time.
The synchronized Key Word Compulsory we have to Define within a Method and it
Still if the Lock is Unavailable then Thread can Continue its Execution.
is Not Possible to Declare Over Multiple Methods.
Eg: if (l.tryLock(1000, TimeUnit.SECONDS)) {}
To Overcome Above Problems SUN People introduced java.util.concurrent.locks
Package in 1.5 Version.
It Also Provides Several Enhancements to the Programmer to Provide More Control
on Concurrency. TimeUnit:TimeUnit is an enum Present in java.util.concurrent Package.
Lock(I): enumTimeUnit {
DAYS, HOURS, MINUTES, SECONDS, MILLI SECONDS, MICRO SECONDS, NANO SECONDS;
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 4) void lockInterruptedly();
Implicit Locks.
Acquired the Lock Unless the Current Thread is Interrupted.
Acquires the Lock if it is Available and Returns Immediately.
If it is Unavailable then the Thread will wait while waiting if it is Interrupted then it
won’t get the Lock.
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
Important Methods of Lock Interface Issue.
1) void lock(); Internally ReentrantLock Increments Threads Personal Count whenever we Call
It Locks the Lock Object. lock() and Decrements Counter whenever we Call unlock() and Lock will be
If Lock Object is Already Locked by Other Thread then it will wait until it is Released whenever Count Reaches ‘0’.
Unlocked.
Constructors:
2) booleantryLock(); 1) ReentrantLockrl = new ReentrantLock();
Creates an Instance of ReentrantLock.
To Acquire the Lock if it is Available.
If the Lock is Available then Thread Acquires the Lock and Returns true.
2) ReentrantLockrl = new ReentrantLock(boolean fairness);
If the Lock Unavailable then this Method Returns false and Continue its
Creates an Instance of ReentrantLock with the Given Fairness Policy.
Execution.
In this Case Thread is Never Blocked.
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
89 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
90 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
If Fairness is true then Longest Waiting Thread can acquired Lock Once it is
Avaiable i.e. if follows First - In First – Out. 8) intgetQueueLength(); Returns the Number of Threads waiting for the Lock.
If Fairness is false then we can’t give any Guarantee which Thread will get the
Lock Once it is Available. 9) Collection getQueuedThreads(); Returns a Collection containing Thread Objects
Note: If we are Not specifying any Fairness Property then by Default it is Not Fair. which are waiting to get the Lock.
10) booleanhasQueuedThreads(); Returns true if any Thread waiting to get the Lock.
1) void lock();
2) booleantryLock();
4) void lockInterruptedly();
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
5) void unlock();
System.out.println(l.isLocked()); //true
To Realease the Lock.
If the Current Thread is Not Owner of the Lock then we will get Runtime l.unlock();
Exception Saying IllegalMonitorStateException. System.out.println(l.isLocked()); //false
System.out.println(l.isFair()); //false
6) intgetHoldCount(); Returns Number of Holds on this Lock by Current Thread. }
}
7) booleanisHeldByCurrentThread(); Returns true if and Only if Lock is Hold by
Current Thread.
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
91 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
92 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR JAVA Means DURGASIR
If we Comment Both Lines 1 and 2 then All Threads will be executed Simultaneously
importjava.util.concurrent.locks.ReentrantLock; and Hence we will get Irregular Output.
class Display {
ReentrantLock l = new ReentrantLock(true); If we are Not Commenting then the Threads will be executed One by One and Hence we
public void wish(String name) { will get Regular Output
l.lock(); 1
Good Morning
for(int i=0; i<5; i++) {
Dhoni
System.out.println("Good Morning");
Good Morning
try { Demo Program To Demonstrate tryLock();
Dhoni
Thread.sleep(2000);
Good Morning
}
Dhoni importjava.util.concurrent.locks.ReentrantLock;
catch(InterruptedException e) {}
Good Morning classMyThread extends Thread {
System.out.println(name);
Dhoni staticReentrantLock l = new ReentrantLock();
}
Good Morning MyThread(String name) {
l.unlock(); 2
Dhoni super(name);
}
Good Morning }
}
Yuva Raj public void run() {
classMyThread extends Thread {
Good Morning if(l.tryLock()) {
Display d;
Yuva Raj SOP(Thread.currentThread().getName()+" Got Lock and Performing Safe Operations");
String name;
Good Morning try {
MyThread(Display d, String name) {
Yuva Raj Thread.sleep(2000);
this.d = d;
Good Morning }
this.name = name;
Yuva Raj catch(InterruptedException e) {}
}
Good Morning l.unlock();
public void run() {
Yuva Raj }
d.wish(name);
Good Morning else {
}
ViratKohli System.out.println(Thread.currentThread().getName()+" Unable To Get Lock
}
Good Morning and Hence Performing Alternative Operations");
classReentrantLockDemo {
ViratKohli }
public static void main(String[] args) {
Good Morning }
Display d = new Display();
ViratKohli }
MyThread t1 = new MyThread(d, "Dhoni");
Good Morning classReentrantLockDemo {
MyThread t2 = new MyThread(d, "Yuva Raj");
ViratKohli public static void main(String args[]) {
MyThread t3 = new MyThread(d, "ViratKohli");
Good Morning MyThread t1 = new MyThread("First Thread");
t1.start();
t2.start(); ViratKohli MyThread t2 = new MyThread("Second Thread");
t3.start(); t1.start();
} t2.start();
} }
}
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
93 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
94 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
Thread Pools:
importjava.util.concurrent.TimeUnit;
importjava.util.concurrent.locks.ReentrantLock;
Creating a New Thread for Every Job May Create Performance and Memory
classMyThread extends Thread {
Problems.
staticReentrantLock l = new ReentrantLock();
MyThread(String name) { To Overcome this we should go for Thread Pool Concept.
super(name); 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.
public void run() { Thread Pool Framework is Also Known as Executor Framework.
do { We can Create a Thread Pool as follows
try { ExecutorService service = Executors.newFixedThreadPool(3);//Our Choice
if(l.tryLock(1000, TimeUnit.MILLISECONDS)) { We can Submit a Runnable Job by using submit().
SOP(Thread.currentThread().getName()+"------- Got Lock"); service.submit(job);
Thread.sleep(5000); We can ShutdownExecutiorService by using shutdown().
l.unlock(); service.shutdown();
SOP(Thread.currentThread().getName()+"------- Releases Lock");
break; importjava.util.concurrent.ExecutorService;
} importjava.util.concurrent.Executors;
else { classPrintJob implements Runnable {
SOP(Thread.currentThread().getName()+"------- Unable To Get Lock And Will Try Again"); String name;
} PrintJob(String name) {
} this.name = name;
catch(InterruptedException e) {} }
} public void run() {
while(true); SOP(name+"....Job Started By Thread:" +Thread.currentThread().getName());
} try {
} Thread.sleep(10000);
classReentrantLockDemo { }
public static void main(String args[]) { catch (InterruptedException e) {}
MyThread t1 = new MyThread("First Thread"); SOP(name+"....Job Completed By Thread:" +Thread.currentThread().getName());
MyThread t2 = new MyThread("Second Thread"); }
t1.start(); }
t2.start(); class ExecutorDemo {
} public static void main(String[] args) {
} PrintJob[] jobs = {
newPrintJob("Durga"),
First Thread------- Got Lock newPrintJob("Ravi"),
Second Thread------- Unable To Get Lock And Will Try Again newPrintJob("Nagendra"),
Second Thread------- Unable To Get Lock And Will Try Again newPrintJob("Pavan"),
Second Thread------- Unable To Get Lock And Will Try Again newPrintJob("Bhaskar"),
Second Thread------- Unable To Get Lock And Will Try Again newPrintJob("Varma")
Second Thread------- Got Lock };
First Thread------- Releases Lock ExecutorService service = Executors.newFixedThreadPool(3);
Second Thread------- Releases Lock for (PrintJob job : jobs) {
service.submit(job);
}
service.shutdown();
}
}
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
95 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
96 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR JAVA Means DURGASIR
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).
importjava.util.concurrent.Callable;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.Future;
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?
FAQ’S 22) If 2 Threads Having Different Priority Then Which Thread Will Get Chance First
For Execution?
4) When Compared With C++ What Is The Advantage In Java With Respect To Multi
Threading?
10) Is It Possible Overloading Of run()? 23) If 2 Threads Having Same Priority Then Which Thread Will Get Chance First For
Execution?
11) Is It Possible To Override a start() And What Will Happen?
24) How We Can Prevent Thread From Execution?
12) Explain Life Cycle Of A Thread?
25) What Is yield() And Explain Its Purpose?
nd nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
99 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
100 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGASIR JAVA Means DURGASIR
26) Is Join Is Overloaded? 49) What Is Starvation And Explain Difference Between Deadlock and Starvation?
28) What Is synchronized Key Word? Explain Its Advantages And Disadvantages? 51) What Is Daemon Thread? Give An Example Purpose Of Daemon Thread?
29) What Is Object Lock And When It Is Required? 52) How We Can Check Daemon Nature Of A Thread? Is It Possible To Change
Daemon Nature Of A Thread? Is Main Thread Daemon OR Non-Daemon?
30) What Is A Class Level Lock When It Is Required?
53) Explain About ThreadGroup?
31) While A Thread Executing Any Synchronized Method On The Given Object Is It
Possible To Execute Remaining Synchronized Methods On The Same Object 54) What Is ThreadLocal?
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?