MULTI-THREADING
MULTI-THREADING
40]***************************
*** INTRODUCTION:
-----------------
**WHAT IS MULTI-TASKING ?
ANS: executing several tasks simultaneously.
**Imp-Note:
-----------
CASE 1: if multiple threads waiting to execute then which thread will execute
decided by " Thread Schedular " which is part of JVM.
Note:- without Thread class start() method , there is no chance of starting a new
thread in java, due to this start() is considerd as heart of multithreading.
1 once we create a Thread obj-> then its called new state or born state.
3 if sheduler allocates CPU -> then Thread will be entered into running state.
4 once run method completes -> then thread will be intered into dead state.
CASE 9:
>after starting a thread we are not allowed to restart same thread once again. else
get IllegalTreadStateException.
** CASE STUDY:
---------------
CASE 1 : t1.start()
-------------------
a new thread will be created , which execute Thread class run() method.
so here op comes only from main thread not child thread.
CASE 2 : t1.run()
-------------------
new thread will not created , Thread class run() method executed like normal
method call.
so here op comes only from main thread not child thread.
CASE 3 : t2.start()
-------------------
a new thread will be created , which execute MyRunnable class run() method.
so here op comes from both main thread and child thread.
CASE 4 : t2.run()
-------------------
new thread will not be created , MyRunnable class run() method.just like normal
method.
so here op comes from both main thread and child thread.
CASE 5 : r.start()
-------------------
CE:- start() method is not in MyRunnable.
CASE 6 : r.run()
-------------------
new thread will not be created , MyRunnable class run() method.just like normal
method.
so here op comes from both main thread and child thread.
Note
every thread in java has some name , it may provided by explicitally by programmer
or jvm.
ex:
Thread.currentThread().setName("Bhaskar Thread");
** THREAD PRIORITIES:
---------------------
>every thread in java has some prority , it may default generated by JVM or
explicitally provided by programmer.
> thread range is 1 to 10 , not 0-10, where 1 is the least priority and 10 is
high priority.
Note: if 2 threads having same priority then we can not expect execution order.
Q-how to get thread priority
ans: 2 methods are
** DEFAULT PRIORITY:
---------------------
> allowed only for main method thread is 5. but for all remaining threads default
prirority will be inheriting from parent to child.
means whatever parent has priority same will be for child also.
1 yield()
2 join()
3 sleep()
1 yield():- to pause current executing thread for giving chance to remaing waiting
threads of same priority.
----------
1= but if all waiting thread have low priority
or
if there is no waiting thread -->then same thread will be continue.
2=>if several waiting threads of same priority then we can not expect order.
DIAG:
________thread.yield()[Runable <= running back]
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead
2 join(): use if a thread want to wait until completing other thread .
---------
its mehtods:
DIAG:
_________[waiting state]_________________
| |
|1- if t1 complete or |1-t2.join()
|2- if time expires or |2-t2.join(1000)
|3- if waiting got interruptted |3-t2.join(1000,100)
| |
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead
** Imp note:- if main td calls join on child td , and child td calls join on main
td obj then both td will wait for each other forever
and program will be hanged.
3 sleep() :
-----------
if a thread do not want to perform any operation for a particular amount of time
then use sleep().
_________[waiting state]_________________
| |
| |
|1- if time expires or |1-t2.join(1000)
|2- if waiting got interruptted |2-t2.join(1000,100)
| |
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead
**INTERRUPTING A THREAD ?
-------------------------
if a thread can interrupt a sleeping or waiting thread by using interrupt() method
of thread class.
ex : public void interrupt();
Note:- if a thread want to execute any syncronized method on given obj then
first it has to get lock of that object.
once a thread got lock then its allowed to execute any syncronized method on
that object.
and after execution completion automatically thread release lock.
Note:- remaining thread are not allowed execute syncronized method simultancialy
but remaining threads allowed to execute non syncronized method simultancially.
[Note:- lock concept is impl based on object but not based on method]
IMP NOTE:
1 if multiple threads are operating on multiple objects then there is no impact of
syncronization
2 if multiple threads are operating on same objects then there is require
syncronization.
Q** class level lock:-
--------------------
1- every class in java has a unique lock. if a thread wants to execute a static
syncronized mehtod then it req class level lock.
2 once a thread got class level lock then it is allow to execute any static
syncronized mehtod .
3 class level lock and object level lock both are diff and there is no
relationship bw these two.
> to get class level lock we have to declare syncronized block , we can pass obj
ref or .class file and we can not pass primitive values as argument. because lock
concept is depend only for object and class but not for primitives.
> Two thread can communicate with each other by using wait(), notify() , and
notifyAll() mehtods.
> Thread which is required updation it has to call wait() mehtod on the req obj
then immediately the thread will entered into waiting state.
the thread which is performing updation of object , its responsible to give
notification by calling notify() method.
> after getting notification the waiting Thread will get updations.
> wait, notify, and notifyAll methods are avaible in object class but not in thread
class because thread can call these method on any common object.
ex:
1- current thread should has lock of that object
2- current thread should be in syncronized area. so we can call wait(),notify(),
notifyAll() methods only from syncronized area else get RE.
> once a thread calls wait() method on given object , first it release the lock of
that object immediataly and entered into waiting state.
except these[wait, notify, and notifyAll methods] there is no other place [method]
the lock release happen.
Q-in how many method can release lock ?
ans:-3 - wait, notify, notifyAll
** notify Vs notifyAll():
-------------------------
> we can use notify() to give notification for only one thread
and if multiple threads are waiting then one thread will get chance and remaining
threads has to wait for further notification.
but which thread will be notify(inform) we can not expect exactly its depends on
JVM.
> we can use notifyAll() method to give notification for all waiting threads. All
threads will be notified and will be executed one by one ,
because they required lock.
Q1 Once a thread call wait on any object, immediataly it will entered into waiting
state without releasing the lock ?
ans: No
Q2 Once a thread call wait on any object , it reduce the lock of that object but
may not immediately ?
ans: No
Q3 Once a thread call wait on any object , it immediataly release all locks
whatever it has and entered into waiting state ?
ans: No
Q4 Once a thread call wait on any object , it immediataly release lock of that
perticular object and entered into waiting state ?
ans: YES
Q5 Once a thread call notify() on any object , it immediataly release lock of that
object?
ans: NO
Q5 Once a thread call notify() on any object , it release lock of that object ,
but not immediataly ?
ans: yes
** DEAD-LOCK :-
----------------
if 2 threads are waiting for each other forever (without end), this situation
(infinite waiting) is called dead lock.
Note:- there are no resoluation for dead lock but several prevention [avoidance
technics ] are possible.
Note:- Syncronized kw is the cause for deadlock, so while using it take care.
imp-note:- if we remove syncronized keyword some where then we will not get
DeadLock.
so syncronized kw only one reason for DeadLock due to this we have to handling
carefully.
** Deamon -Threads:-
--------------------
Def:-threads which are executing in background are called daemon threads.
the main objective of daemon threads is to provide support for non daemon
threads like main thread.
ex:- Garbage collector:- when our program runs with low memory , then jvm will
execute GC to provide free memory so that main thread can continue its execution.
> we can change daemon natur of a thread by using setDaemon() method but befor
starting thread only but not after starting.
> Note:- Main thread is always non daemon and for remaining threads daemon natur
will be inheriting from parent to child ,if parent is daemon child also daemon.
> whenver last non daemon thread terminates automatically all daemon threads will
be terminated.
**Lazy thread:-
---------------
if main thread is non daemon and child thread is daemon and whenver main thread
terminates automatically child thread will be terminated.
** DEADLOCK VS STARVATION :-
----------------------------
> a long waiting of a thread which never ends is called deadlock.
> a long waiting of a thread which ends at certain point is called starvation.
Q- HOW TO KILL A THREAD IN THE MIDDLE OF THE LINE ?
---------------------------------------------------
we can call stop() method to stop a thread in the middle then it will entered into
dead state immediatally.
public final void stop();
Note:- but stop method has deprecated and not recommended to use.
** ThreadGroup:-
----------------
> based on functionality we can group threads as a single unit which is nothing but
ThreadGroup.
> ThreadGroup provides a way to common operations for all threads belongs to a
perticular group.
Q- ThreadLocal ?
----------------
ans:- we can use threadLocal to define local resources which are required for a
perticular Thread like DBConnecitons, CounterVars.
we use ThreadLocal to define Thread scope like Servlet scope (page, request,
session, application).
Q- GreenThread ?
----------------
ans:- java multithreading concept is implementing by using following 2 methods.
1 GreenThread Model
2 Native OS Model
Note:-
1 GreenThread:-the threads which are managed completely by JVM wihtout taking
support for underlying OS, called Green Threads.
2 Native OS :- the threads which are managed with the help of underlying OS .
VVIMP:
Q-Life Cycle of a thread ? [ans- see video and pictur in 80 page.]
Q- what is diff bw extends Thread and implement Runnable ? and which is better ?
ans:
1 extends Thread:- useful to override public void run() of Thread class.
2 implement Runnable:-useful to implement public void run() of Runnable interface.
Q *** Note:- read all given q on thread and give ans for interview -vedio 14 page
81]
================= MULTITHREADING
ENHANCEMENT================================================
1 ThreadGroup
2 ThreadLocal
3 java.util.concurrent.locks package
Lock(I)
ReentrantLock(C)
4 Thread Pools
5 Callable and Future
----------------------------------
1 ThreadGroup:-
----------------
> based on functionality we can group threads as a single unit which is nothing but
ThreadGroup.
> ThreadGroup represent a set of Threat . it also contains other subthreadGroups.
> ThreadGroup provides a way to common operations for all threads belongs to a
perticular group.
> ThreadGroup class present in java.lang package its direct child of object.
** CONSTRUCTOR:-
----------------
Note:-
1- in java, every thread belongs to some group.
2 every ThreadGroup is the child group of System Group either directally or
indirectally. so System Group acts as a root for all ThreadGroup in java.
3 System ThreadGroup represents System Level Threads Like ReferenceHandler,
SignalDispatcher, Finalizer, AttachListener.
3 void setMaxPriority();
>to set max priority of the ThreadGroup
>default max priority is 10
> threads in the ThreadGroup that already have higher priority , not effected
but newly added threads this applicable.
8 int enumerate(Thread[] t); // to copy all active threads of this group into
provided thread array. and subthreadgroup also included.
10 boolean isDaemon();
2 ThreadLocal:
==============
>thread local provide local vars.
> maintains values for thread basis.
> each ThreadLocal obj maintain a seprate value like userID, transactionId for each
thread that access that object.
> thread can access its local value, can manipulate its value and even can remove
its value.
vvi
Q- in real time where we use this ThreadLocal ?
ans:- see ans page 89
Note:-
>ThreadLocal can be associated with scope.
>all code which is executed by thread has access to correspondence ThreadLocal
vars.
>a thread can access only its own local vars not other threads vars.
>once thread entered into Dead state all local vars are by default eligible for GC.
Q- ThreadLocal Vs InheritanceThreadLocal ?
InheritanceThreadLocal
method and constructors
--------------------------------------------------------------------------------
3 JAVA.UTIL.CONCURRENT.LOCKS PACKAGE:
-----------------------------------------
2 we can not specify maximum waiting time for a thread to get lock so it will until
getting lock,
3 not flexibilty with try
4 no API to list all waiting threads for a lock.
5 the syncronized kw is compulsory to define within a method
Lock(I):
--------
>a lock Object is similar to implicit Lock acquired by thread to execute
syncronized method or block.
>lock implementations provide more extensive operations then tradition locks.
4 THREAD POOLS:
=================
its pool of already created threads ready to do our job.
> java 1.5 v introduced Thread Pool framwork to impl thread pools.
> Thread Pool framwork is also known as executor framwork.
-----------------------------------------------------------------------
5 CALLABLE AND FUTURE:
======================
> if a thread req to return some result after execution then use callable
> callable interface contains only one method
public Object call() throws Exception.
> if we submit a callable object to executor then framwork return an Object of type
java.util.concurrent.Future
> the future Object can be used to retrive the result from Callable job.
** VVIMP NOTE:- READ AND WATCH ALL IMP Q GIVEN AT PAGE 103
------------------------------------------------------------