MultiThreading
Q. What is Multithreading?
A. Multithreading in java is a process of
executing multiple threads simultaneously.
Q. What is process?
A. A process is an instance of a computer program that
is being executed.
Q. What is Thread in java?
A. A tread is a light weight process. A thread class belongs to java.lang package.
We can create
multiple threads in java, even if we don’t create any Thread, one Thread at
least do exist i.e. main thread. Multiple threads run parallely in java.
Q. What is difference between Process and Thread in
java?
Thread
|
Process
|
1.
Threads
are subdivision of Process. One or more Threads runs in the context of
process.
2. Threads have direct access to the data
segment of its process.
3. Threads share the address space of the
process that created it.
4. Thread is light weight process.
5. Thread has its own
stack.
|
1. Same part of process can be executed
by multiple Threads.
2.
Processes
have their own copy of the data segment of the parent process.
3. Processes have their own address.
4. Process is heavy weight.
5.
In process all threads share system resource like
heap Memory.
|
Q. What is life cycle of Thread, explain thread states?
New: When we create an instance of
Thread class, a thread is in a new state, but the start() method has
not been invoked on the thread yet, thread is not eligible to run yet. Thread
object is considered alive but thread is not alive yet.
Runnable: When start() method is called on thread it
enters runnable state.
·
As
soon as Thread enters runnable state it is eligible to run, but not running.
(Thread scheduler has not scheduled the Thread execution yet, Thread has not
entered in run() method yet).
·
A
thread first enters the runnable state when the start() method is invoked, but
a thread can also return to the runnable state after either running or coming
back from a blocked, waiting, or sleeping state.
·
Thread
is considered alive in runnable state.
·
Thread
is in Runnable pool.
Running: Thread scheduler selects
thread to go from runnable to
running state. In running state Thread starts executing by entering run()
method.
Thread scheduler selects thread from the runnable pool on
basis of priority, if priority of two threads is same; threads are scheduled in
unpredictable manner. Thread scheduler behavior
is completely unpredictable.
When threads are in running state, yield() method can make thread to go in
Runnable state.
Waiting/blocking/sleeping: In
this state a thread is not eligible to run. Thread is still alive, but currently
it’s not eligible to run. In other words:
Q.
How can Thread go from running to waiting state?
A. By calling wait() method thread go from running to waiting state. In waiting
state it will wait for other threads to release object monitor/lock.
Q.
How can Thread return from waiting to runnable state?
A. Once notify()
or notifyAll() method is called object monitor/lock becomes available and
thread can again return to runnable state.
Q.
How can Thread go from running to sleeping state?
A. By calling sleep() method thread go from running to sleeping state. In sleeping
state it will wait for sleep time to get over.
Q.
How can Thread return from sleeping to runnable state?
A. Once specified sleep time is up thread can again return to runnable state.
Suspend():
method can be used to put thread in waiting state and resume() method is the only way which could put thread in runnable
state.
Thread
also may go from running to waiting state if it is waiting for some I/O
operation to take place. Once input is available thread may return to running
state.
Terminated: A
thread is considered dead when its
run() method completed. Once thread is dead it cannot be started again
doing so will throw runtimeException i.e. IllegalThreadStateException.
destroy() method puts thread directly into dead state.
Q. How to implement Threads in java?
A. Threads can be created in two ways by
implementing java.lang.Runnable
interface or by extending java.lang.Thread
class.
Example
of implementing java.lang.Runnable:
Example
of extending java.lang.Thread:
Q. What are differences between implementing
Runnable and extending Thread?
implementing Runnable
|
extending Thread
|
1.
If class
implements Runnable interface, It can extend other class.
2.
Multiple threads
shares same objects.
3.
As multiple
threads share same object less memory is used.
4. when we implement Runnable interface
no extra feature are inherited,
as Runnable only consists only of one abstract method i.e. run() method
|
1. Java doesn’t support multiple inheritance so after
extends Thread class. It can’t extend any other class.
2. Each thread create unique object and associated with
it.
3. As each thread create unique object, more memory
required.
4. When we extend Thread unnecessary all Thread class features are
inherited
|
Note:
Recommendation to go for implementing
Runnable rather than extending Thread class.
Q. Does Thread implements their own Stack, if yes how?
A. Yes. Thread has their own stack.
Q. How can you say Thread behavior is unpredictable?
A. Thread behavior is unpredictable because execution of Threads
depends on Thread scheduler, thread scheduler may have different implementation
on different platforms like windows, Unix etc. Same threading program may
produce different output in subsequent executions even on same platform.
See
below example:
Q. When threads are not lightweight process in java?
A. Threads are lightweight
process only if threads of same process are executing concurrently. But if
threads of different processes are executing concurrently then threads
are heavy weight process.
Q. What is run() and start()
methods?
A. run(): Entry point of thread.
start(): The start() method
of thread class is used to begin the execution of thread. start() internally
call run() method.
Q. How can you ensure all threads that started from main must end in order
in which they started and also main should end in last?
A.
We can use join ()
method to ensure all threads that started from main must end in order in which
they started and also main should end in last.
Q. What is Join () method in java?
A. joint (): join () method can be used to pause the current thread
execution until unless the specified thread is dead. It is an instance method of java.lang.Thread class which we can use join () method to ensure all threads
that started from main must end in order in which they started and also main
should end in last.
Note: thread need not to acquire object lock before
calling join() method i.e.
join() method can be called from
outside synchronized block.
1. join() : Waits for this thread to die.
public final
void join() throws
InterruptedException;
2. join(long millis) - Waits at most millis milliseconds for this thread to die.
A timeout of 0 means to wait forever.
public static
native void join(long
millis) throws
InterruptedException;
3. join(long millis, int nanos) - Waits at most millis milliseconds plus nanos
nanoseconds for this thread to die.
public static native void join(long millis,int nanos) throws
InterruptedException;
Q. What is difference between
starting thread with run() and start() method?
A. When we call start()
method, main thread internally calls run() method to start newly created
Thread, so run() method is ultimately called by newly created thread.
When we
call run() method main thread rather
than starting run() method with newly thread it start run() method by itself.
Q. Can you again start Thread?
A. No. we can’t start thread again.
It will
throw runtimeException java.lang.IllegalThreadStateException.
The reason is once run() method is executed by Thread, it goes into dead state.
Q. What is sleep()?
A. sleep() is a static method. It pause the execution of current thread for specified milliseconds and
nanoseconds. JVM provide the implementation of sleep().
when sleep() is called on thread it goes
from running to waiting state and can return to runnable state when sleep
time is up. sleep() method throws compile time exception i.e. InterruptedException.
sleep(long
millis) - Causes the
currently executing thread to sleep for the specified number of milliseconds.
public static native void
sleep(long millis) throws InterruptedException;
2.
sleep(long millis,
int nanos) - Causes the currently executing thread to
sleep for the specified number of milliseconds plus the specified number of
nanoseconds.
public static native void sleep(long
millis,int nanos) throws InterruptedException;
Q. What is yield()?
A. yield() method pauses the currently
executing thread temporarily for giving a chance to the remaining waiting
threads of the same priority to execute. If there is no waiting thread or all
the waiting threads have a lower priority then the same thread will continue
its execution.
yield()
is a static method, hence calling Thread.yield() causes currently
executing thread to yield.
when yield()
method is called on thread it goes
from running to runnable state, not in waiting state. Thread is eligible
to run but not running and could be picked by scheduler at the discretion of
the implementation.
public static native void
yield();
MOTE: synchronized block : thread need not to to acquire object lock
before calling yield() method
i.e. yield() method can be called from
outside synchronized block.
Below is
the yield exmaple
Q. What wait(), notify() and notifyAll() method?
A. notify():Wakes up a single thread
that is waiting on this object's monitor. If many threads are waiting on this
object, one of them is chosen to be awakened. The choice is random and occurs at
the discretion of the implementation. A thread waits on an object's monitor by
calling one of the wait methods.
Syntax:
public final native void notify();
The awakened threads will not be able to proceed
until the current thread leave the lock on this object.
·
By
executing a synchronized instance method of that object.
·
By
executing the body of a synchronized statement that synchronizes on the object.
·
For
objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
notifyAll():Wakes
up all threads that are waiting on this object's monitor. A thread waits on an
object's monitor by calling one of the wait methods.
The awakened threads will not be able to proceed
until the current thread leave the lock on this object.
Syntax: public final native void notifyAll();
Wait():Causes the current thread to wait until another thread
invokes the notify() or notifyAll() method for this object.
The
current thread must own this object's monitor. The thread releases ownership of
this monitor and waits until another thread notifies threads waiting on this
object's monitor to wake up either through a call to the notify()/ notifyAll()
method. The thread then waits until it can re-obtain ownership of the monitor
and resumes execution. It tells the calling
thread to give up the lock and go to sleep until some other thread enters the
same monitor and calls
notify() or
notifyAll().
Thread State:
By
calling wait() method thread go from running to waiting state. In
waiting state it will wait for other threads to release object monitor/lock.
Once notify() or notifyAll() method is called object monitor/lock becomes
available and thread can again return to runnable state.
Wait() has three overloaded methos:
1. wait() - It internally calls wait(0).
2. wait(long timeout) - Causes the current thread to wait
until either another thread invokes the notify() or notifyAll() methods for
this object, or a specified timeout time has elapsed.
public final native void wait(long timeout)
throws InterruptedException;
3. wait(long timeout, int nanos) - Causes the current thread to wait
until either another thread invokes the notify() or notifyAll() methods for
this object, or a specified timeout time plus the specified number of nanoseconds
has elapsed.
public static native void wait(long
timeout,int nanos) throws InterruptedException;
Note:
1.
Synchronized block: thread needs to acquire object lock before calling wait() and notify() methods i.e. these methods can be called only from synchronized block
or synchronized method.
2.
As mentioned above before calling
these methods thread must own object’s monitor means wait() and notify()
methods must be called from synchronized blocks or synchronized method
otherwise IllegalMonitorStateException is thrown at runtime.
3.
Wait() , notify() and notifyAll() are
belongs to java.lang.Object class and these are always called on objects not on
thread
Solve Consumer and Producer problem using
wait(), notify() and notifyAll():
In program consumer thread will start() and wait by calling wait() method
till producer is producing. Once production is over, producer thread will call
notify() method, which will notify consumer thread and consumer will start
consuming.
Q. Why wait(), notify() and notifyAll() are in Object
class and not in Thread class?
A.1. Every Object has a monitor, acquiring
that monitors allow thread to hold lock on object. But Thread class does not
have any monitors.
2. wait(),
notify() and notifyAll()are called on objects only >When wait() method is
called on object by thread it waits for another thread on that object to
release object monitor by calling notify() or notifyAll() method on
that object.
Q. How threads
communicate between each other?
A. By using wait(), notify() and notifyAll()
method.
Q. What is race condition in
multithreading and how can we solve it?
A. When more than one thread try to access same resource without
synchronization causes race condition. We can solve race condition by using
either synchronization block or synchronization method. When no two
threads can access same resource at a time phenomenon is also called as mutual
exclusion.
Q.
What is Synchronization?
A. Synchronization ensures
that only a single thread can execute a block or method of code at same time.
We can create Synchronization block or method.
Thread can acquire
object lock by – entering into Synchronization block or method.
1. First let’s acquire object lock by entering synchronized
block.
Let’s say there is one class SynchronizedBlock and we have created it’s
object and reference to that object is obj. Now
we can create synchronization block, and parameter passed with synchronization
tells which object has to be synchronized. In below code, we have synchronized
object reference by obj.
SynchronizedBlock obj=new SynchronizedBlock ();
synchronized (obj) {
//thread has acquired object
lock on object referenced by obj ( by acquiring obj monitor.)
}
As
soon thread entered Synchronization block, thread acquired object lock on
object referenced by obj (by acquiring
object’s monitor.)
Thread
will leave lock when it exits synchronized block.
If we note output, Thread-1 entered synchronization block and acquired obj’s lock meanwhile Thread-2 kept on waiting for obj’s lock. And once Thread-1 completed Thread-2 acquired obj’s lock and started executing.
It’s
important to know that multiple threads may exist on same object but only one thread of that
object can enter synchronized method at a time. Threads on different object can enter same method at same time.
2) Now let’s acquire object lock by entering synchronized
method.
Example- Let’s say there is one class SynchronizedMethod and we have created it’s
object and reference to that object is obj. Than
we started thread and from run method we called synchronized void
method1().
public synchronized void
method1() {
//thread has acquired object
lock on object referenced by obj ( by acquiring obj monitor.)
}
As soon as thread entered Synchronization method, thread acquired object lock on object referenced by obj (by acquiring object’s monitor.)
Thread
will leave lock when it exits synchronized method.
It’s
important to know that multiple threads may exist on same object but only one thread of that
object can enter synchronized method at a time. Threads on different object can enter same method at same time.
If we note output, Thread-1
entered synchronized method and acquired obj’s lock meanwhile Thread-2 kept on
waiting for obj’s lock. And once Thread-1 completed Thread-2 acquired obj’s lock
and started executing.
Q. what
is volatile?
A. Declaring a volatile Java
variable means:
The value of this variable will never be cached
thread-locally: all reads and writes will go straight to "main
memory";
Access to the variable acts as though it is
enclosed in a synchronized block, synchronized on itself.
NOTE:
1. If a field is declared volatile, in that case the Java memory model ensures
that all threads see a consistent value for the variable.
2. Volatile can be used as a keyword against the
variable, we cannot use volatile against method declaration.
3. Volatile keyword
can be used as an alternate to synchronization in java, as all threads
always have access to latest updated value.
4. Using volatile is better than synchronization, as
synchronization needs to block whole method (if used in method declaration) or
block (if synchronization block is used), while volatile needs not to block
any piece of code.
5. Not Cached in CPU- Volatile members are
never cached in CPU by jvm, they are always read from main memory
i.e. from stack where variable lives.
It is possible for multiple CPU’s to exist on
machine, so it is possibility that thread might cache different values in
different CPU’s for same variable, so it’s important that value is not
cached in CPU and always read from main memory.
6. Volatile keyword must be used in multithreading environment,
there is no use of using volatile keyword in non multi threading environment,
it may cost us unnecessary performance issue as volatile keyword is not cached
in memory by jvm.
7. If variable
which has been declared volatile, is a reference to object it may point to null
as well, volatile Integer i=null; //it’s allowed.
8. A compile-time
error will occur if a final variable is declared volatile.
volatile final int x = 0; //The
field x can be either final or volatile, not both.
9. Performance
issue - As volatile keyword is not cached in CPU, it is always read from
main memory, so in terms of performance it’s always expensive to use volatile
keyword.
Q. Can we
have volatile methods in java?
A. No, volatile is only a keyword, can be used only with variables.
Q. Can we have synchronized variable
in java?
A. No, synchronized can be used only with methods, i.e. in
method declaration.
volatile
|
synchronized
|
1.
volatile can be used as a keyword
against the variable, we cannot use volatile against method declaration.
2.
volatile does not acquire any lock on
variable or object.
3.
volatile variables are not cached.
4.
When volatile is used will never create deadlock in
program, as volatile never obtains any kind of lock.
5.
volatile is never expensive in terms of performance.
|
1.
synchronization can be used in method
declaration or we can create synchronization blocks (In both cases thread
acquires lock on object’s monitor). Variables cannot be synchronized.
2.
synchronization acquires lock on method
or block in which it is used.
3.
variables used inside synchronized method or block
are cached.
4.
But in case if synchronization is not done properly,
we might end up creating dedlock in program.
5.
Synchronization may cost us performance issues, as
one thread might be waiting for another thread to release lock on object.
|
Q. What are daemon threads?
A. Daemon
threads are low priority threads which run intermittently in background
for doing garbage collection. daemon thread is a service provider
to serves other threads.
Ø These threads are created before
user threads are created and die after all other user threads dies.
Ø Priority of daemon threads is always 1
(i.e. MIN_PRIORITY).
Ø User created threads is non daemon
threads.
Ø JVM can exit when only daemon threads exist in
system.
Ø we can use isDaemon() method to
check whether thread is daemon thread or not.
Ø we can use setDaemon(boolean on)
method to make any user method a daemon thread. Generally, We must not make
user threads as daemon.
Ø If setDaemon(boolean on) is
called on thread after calling start() method than IllegalThreadStateException is
thrown.
Q. Is it important to acquire object lock before calling
wait(), notify() and notifyAll()?
A. Yes,
it’s mandatory to acquire object lock before calling these methods on object.
As discussed above wait(), notify() and notifyAll() methods are always
called from Synchronized block only, and as soon as thread enters
synchronized block it acquires object lock (by holding object monitor). If we
call these methods without acquiring object lock i.e. from outside synchronize
block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait()
method needs to enclosed in try-catch block, because it throws compile time
exception i.e. InterruptedException.
Q. Are
you aware of preemptive scheduling and time slicing?
A. In
preemptive scheduling, the highest priority thread executes until it enters
into the waiting or dead state.
In time
slicing, a thread executes for a certain predefined time and then enters
runnable pool. Than thread can enter running state when selected by thread
scheduler.
Q. Why suspend()
and resume() methods are deprecated?
A. Suspend() method is deadlock prone. If the
target thread holds a lock on object when it is suspended, no thread can lock
this object until the target thread is resumed. If the thread that would resume the target
thread attempts to lock this monitor prior to calling resume, it results in
deadlock formation.
These deadlocksare generally called Frozen processes.
Suspend()
method puts thread from running to waiting state. And thread can go from waiting to
runnable state only when resume() method is called on thread. It is deprecated
method.
Resume()
method is only used with suspend() method that’s why it’s also deprecated
method.
Q. Why
destroy() methods is deprecated?
Answer.
This question is again going to check your in depth knowledge of thread methods
i.e. destroy() method is deadlock prone. If the target thread holds a lock on
object when it is destroyed, no thread can lock this object (Deadlock formed
are similar to deadlock formed when suspend() and resume() methods are used
improperly). It results in deadlock formation. These deadlocksare generally called Frozen processes.
Additionally
you must know calling destroy() method on Threads throw runtimeException i.e.
NoSuchMethodError. Destroy() method puts thread from running to dead state.
Q. As
stop() method is deprecated, How can we terminate or stop infinitely
running thread in java? (Important)
Answer.
This is very interesting question where interviewees thread basics basic will
be tested. Interviewers tend to know user’s knowledge about main thread’s and
thread invoked by main thread.
We will
try to address the problem by creating new thread which will run infinitely
until certain condition is satisfied and will be called by main Thread.
1.
Infinitely
running thread can be stopped using boolean variable.
Let’s
understand Why stop() method is deprecated :
Stopping a
thread with Thread.stop() causes it to release all of the monitors that it has
locked. If any of the objects previously protected by these monitors were in an
inconsistent state, the damaged objects become visible to other threads, which
might lead to unpredictable behavior.
·
Should
be called from synchronized block :wait() method is always called from
synchronized block i.e. wait() method needs to lock object monitor before object
on which it is called. But sleep() method can be called from outside
synchronized block i.e. sleep() method doesn’t need any object monitor.
·
IllegalMonitorStateException
: if wait() method is called without acquiring object lock than
IllegalMonitorStateException is thrown at runtime, but sleep() methodnever
throws such exception.
·
Belongs
to which class : wait() method belongs to java.lang.Object class but sleep()
method belongs to java.lang.Thread class.
·
Called
on object or thread : wait() method is called on objects but sleep() method is
called on Threads not objects.
·
Thread state : when wait() method is called on object,
thread that holded object’s monitor goes from running to waiting state and can
return to runnable state only when notify() or notifyAll()method is called on
that object. And later thread scheduler schedules that thread to go from from
runnable to running state.
when
sleep() is called on thread it goes from running to waiting state and can
return to runnable state when sleep time is up.
·
When
called from synchronized block :when wait() method is called thread
leaves the object lock. But sleep()method when called from synchronized
block or method thread doesn’t leaves object lock.
Q. Differences and similarities between yield()
and sleep()?
·
Definition
: yield() method when called on thread gives a hint to the thread scheduler
that the current thread is willing to yield its current use of a processor.The
thread scheduler is free to ignore this hint. sleep() methods causes current
thread to sleep for specified number of milliseconds (i.e. time passed in sleep
method as parameter). Ex- Thread.sleep(10) causes currently executing thread to
sleep for 10 millisec.
·
Thread state : when sleep() is called on thread it goes
from running to waiting state and can return to runnable state when sleep time
is up. when yield() method is called on thread it goes from running to runnable
state, not in waiting state. Thread is eligible to run but not running and
could be picked by scheduler at anytime.
·
Exception
: yield() method need not to catch or throw any exception. But sleep() method
must catch or throw compile time exception i.e. InterruptedException.
·
Waiting
time : yield() method stops thread for unpredictable time, that depends on
thread scheduler. But sleep() method have got few options.
1.
sleep(long
millis) - Causes the currently executing thread to sleep for the specified
number of milliseconds
2.
sleep(long
millis, int nanos) - Causes the currently executing thread to sleep for the
specified number of milliseconds plus the specified number of nanoseconds.
yield() and sleep() method belongs to
java.lang.Thread class.
yield() and sleep() method can be called from
outside synchronized block.
yield() and sleep() method are called on
Threads not objects.
Q.
How thread can enter waiting, sleeping and blocked state and how can they go to
runnable state ?
A. This is very prominently asked
question in interview which will test your knowledge about thread states.
And it’s very important for developers to have in depth knowledge of this thread
state transition. I will try to explain this thread state transition by framing
few sub questions. I hope reading sub questions will be quite interesting.
Q. How
can Thread go from running to waiting state?
A. By calling wait()method thread
go from running to waiting state. In waiting state it will wait for other
threads to release object monitor/lock.
Q. How
can Thread return from waiting to runnable state?
A. Once notify() or notifyAll()method is
called object monitor/lock becomes available and thread can again return to runnable
state.
Q. How
can Thread go from running to sleeping state ?
A. By calling sleep() method thread
go from running to sleeping state. In sleeping state it will wait for
sleep time to get over.
Q. How
can Thread return from sleeping to runnable state?
A.
Once specified sleep time is up thread can again return to runnable state.
Suspend() method can be used to put
thread in waiting state and resume() method is the only way which could put
thread in runnable state.
Thread also may go from running to waiting
state if it is waiting for some I/O operation to take place. Once input is
available thread may return to running state.
When threads are in running state, yield()method can
make thread to go in Runnable state.
Q. Does thread leaves object lock when sleep
() method is called?
A. When sleep () method is
called Thread does not leaves object lock and goes from running to waiting
state. Thread waits for sleep time to over and once sleep time is up
it goes from waiting to runnable state.
Q. Does thread leaves object lock when wait()
method is called?
A. When wait () method is
called Thread leaves the object lock and goes from running to waiting
state. Thread waits for other threads on same object to call notify() or
notifyAll() and once any of notify() or notifyAll() is called it goes
from waiting to runnable state and again acquires object lock.
Q . What will happen if we don’t override run
method?
A . This question will test your basic
knowledge how start and run methods work internally in Thread Api.
When we call start() method on thread, it
internally calls run() method with newly created thread. So, if we don’t
override run() method newly created thread won’t be called and nothing will
happen.
As we saw in output, we didn’t override run()
method that’s why on calling start() method nothing happened.
Q. What will happen if we override start method?
A. This question will again test your basic
core java knowledge how overriding works at runtime, what will be called at
runtime and how start and run methods work internally in Thread Api.
When we call start() method on thread, it
internally calls run() method with newly created thread. So, if we override
start() method, run() method will not be called until we write code for calling
run() method.
If we note output. we have overridden start
method and didn’t called run() method from it, so, run() method wasn’t call.
Q. Can we acquire lock on class? What are
ways in which you can acquire lock on class?
A. Yes, we can acquire lock on class’s
class object in 2 ways to acquire lock on class.
Thread can acquire lock on class’s class
object by-
Entering synchronized block or by entering
static synchronized methods.
Answer. It is very important question
from multithreading point of view. We must understand difference between
object lock and class lock to answer interview, ocjp answers correctly.
1. Thread can acquire object lock by-
Entering synchronized block or by entering
synchronized methods.
3
|
1.Thread can acquire lock on class’s
class object by-
Entering synchronized block or by entering
static synchronized methods.
2. Multiple
threads may exist on same or different objects of class but only one thread can
enter static synchronized method at a time.
|
Q. Suppose
you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in
synchronized method1(), can Thread-2 enter synchronized method2() at same time?
A. No, here when Thread-1 is in synchronized
method1() it must be holding lock on object’s monitor and will release
lock on object’s monitor only when it exits synchronized method1(). So,
Thread-2 will have to wait for Thread-1 to release lock on object’s monitor so that
it could enter synchronized method2().
Likewise, Thread-2 even cannot enter
synchronized method1() which is being executed by Thread-1. Thread-2 will have
to wait for Thread-1 to release lock on object’s monitor so that it
could enter synchronized method1().
Q. Suppose
you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in
static synchronized method1(), can Thread-2 enter static synchronized method2()
at same time?
A.No, here when Thread-1 is in static
synchronized method1() it must be holding lock on class class’s object and
will release lock on class’s classobject only when it exits static synchronized
method1(). So, Thread-2 will have to wait for Thread-1 to release
lock on class’s classobject so that it could enter static synchronized
method2().
Likewise, Thread-2 even cannot enter static
synchronized method1() which is being executed by Thread-1. Thread-2 will have
to wait for Thread-1 to release lock on class’s
classobject so that it could enter static synchronized method1().
Q. Suppose
you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in
synchronized method1(), can Thread-2 enter static synchronized method2() at
same time?
A.Yes, here when Thread-1 is in synchronized
method1() it must be holding lock on object’s monitor and Thread-2
can enter static synchronized method2() by acquiring lock on class’s class
object.
Q. Suppose
you have thread and it is in synchronized method and now can thread enter other
synchronized method from that method?
A.Yes, here when thread is in synchronized
method it must be holding lock on object’s monitor and using that
lock thread can enter other synchronized method.
Q. Suppose you have thread and it is in static synchronized
method and now can thread enter other static synchronized method from that
method?
A. Yes, here when thread is in static
synchronized method it must be holding lock on class’s class object and
using that lock thread can enter other static synchronized method.
Q. Suppose you have
thread and it is in static synchronized method and now can thread enter other
non static synchronized method from that method?
A.Yes, here when thread is in static
synchronized method it must be holding lock on class’s class object and
when it enters synchronized method it will hold lock on object’s monitor as
well.
So, now thread holds 2 locks (it’s also
called nested synchronization)-
>first one on class’s class object.
>second one on object’s monitor (This lock
will be released when thread exits non static method).
Q. Suppose you have thread and it is in synchronized method and now can
thread enter other static synchronized method from that method?
Answer.Yes, here when thread is in
synchronized method it must be holding lock on object’s monitor and
when it enters static synchronized method it will hold lock on class’s
class object as well.
So, now thread holds 2 locks (it’s also
called nested synchronization)-
>first one on object’s monitor.
>second one on class’s class object. (This
lock will be released when thread exits static method).
Q. Suppose
you have 2 threads (Thread-1 on object1 and Thread-2 on object2). Thread-1 is
in synchronized method1(), can Thread-2 enter synchronized method2() at same
time?
A.Yes, here when Thread-1 is in synchronized
method1() it must be holding lock on object1’s monitor. Thread-2 will
acquire lock on object2’s monitor and enter synchronized method2().
Likewise, Thread-2 even enter synchronized
method1() as well which is being executed by Thread-1 (because threads are
created on different objects).
Q. Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on
object2). Thread-1 is in static synchronized method1(), can Thread-2 enter
static synchronized method2() at same time?
A. No, it might confuse you a bit that
threads are created on different objects. But, not to forgot that multiple
objects may exist but there is always one class’s class object lock
available.
Here, when Thread-1 is in static synchronized
method1() it must be holding lock on class class’s object and will release lock
on class’s classobject only when it exits static synchronized method1(). So,
Thread-2 will have to wait for Thread-1 to release lock on class’s
classobject so that it could enter static synchronized method2().
Likewise, Thread-2 even cannot enter static
synchronized method1() which is being executed by Thread-1. Thread-2 will have
to wait for Thread-1 to release lock on class’s classobject so
that it could enter static synchronized method1().
Q. Difference between wait() and wait(long
timeout), What are thread states when these method are called?
wait()
|
wait(long timeout)
|
When wait () method is called on
object, it causes causes the current thread to wait until another thread
invokes the notify() or notifyAll() method for this object.
|
wait(long timeout) - Causes the current
thread to wait until either another thread invokes the notify() or
notifyAll() methods for this object, or a specified timeout time has elapsed.
|
When wait( ) is called on object
- Thread enters from running to waiting state.
It waits for some other thread to
call notify so that it could enter runnable state.
|
When wait(1000) is called on object -
Thread enters from running to waiting state. Than even if notify() or notifyAll()
is not called after timeout time has elapsed thread will go from waiting
to runnable state.
|
Q. How
can you implement your own Thread Pool in java?
Q. What is Thread Pool?
ThreadPool is a pool of threads which reuses
a fixed number of threads to execute tasks.
At any point, at most nThreads threads will
be active processing tasks. If additional tasks are submitted when all threads
are active, they will wait in the queue until a thread is available.
ThreadPool implementation internally
uses LinkedBlockingQueue for adding and removing tasks.
In this post i will be using
LinkedBlockingQueue provide by java Api, you can refer this post for implementing
ThreadPool using custom LinkedBlockingQueue.
Need/Advantage of ThreadPool?
Instead of creating new thread every time for
executing tasks, we can create ThreadPool which reuses a fixed number of
threads for executing tasks.
As threads are reused, performance of our
application improves drastically.
Q. How
ThreadPool works?
We will instantiate ThreadPool, in
ThreadPool’s constructor nThreads number of threads are created and started.
ThreadPool
threadPool=new ThreadPool(2);
Here 2 threads will be created and started in
ThreadPool.
Then, threads will enter run() method of
ThreadPoolsThread class and will call take() method on taskQueue.
- If
tasks are available thread will execute task by entering run() method of
task (As tasks executed always implements Runnable).
publicvoid run() {
. . .
while (true) {
. . .
Runnable runnable = taskQueue.take();
runnable.run();
. . .
}
. . .
}
|
- Else
waits for tasks to become available.
When tasks are added?
When execute() method of ThreadPool is called,
it internally calls put() method on taskQueue to add tasks.
taskQueue.put(task);
Once tasks are available all waiting threads
are notified that task is available.
Q. What is significance of using ThreadLocal?
Answer. This question will test your
command in multi threading, can you really create some perfect multithreading
application or not. ThreadLocal is a class which provides thread-local
variables.
Q. What
is ThreadLocal ?
ThreadLocal is a class which provides
thread-local variables. Every thread has its own ThreadLocal value that makes
ThreadLocal value threadsafe as well.
For how long Thread holds ThreadLocal value?
Thread holds ThreadLocal value till it hasn’t
entered dead state.
Can one thread see other thread’s ThreadLocal
value?
No, thread can see only it’s ThreadLocal
value.
Q. Are
ThreadLocal variables thread safe. Why?
Yes, ThreadLocal variables are thread safe.
As every thread has its own ThreadLocal value and one thread can’t see other
threads ThreadLocal value.
Application of ThreadLocal?
- ThreadLocal
are used by many web frameworks for maintaining some context (may be
session or request) related value.
- In
any single threaded application, same thread is assigned for every
request made to same action, so ThreadLocal values will be available in
next request as well.
- In
multi threaded application, different thread is assigned for every
request made to same action, so ThreadLocal values will be different for
every request.
- When
threads have started at different time they might like to store time at
which they have started. So, thread’s start time can be stored in
ThreadLocal.
Creating ThreadLocal >
private
ThreadLocal<String> threadLocal = new ThreadLocal<String>();
We will create instance of ThreadLocal.
ThreadLocal is a generic class, i will be using String to demonstrate
threadLocal.
All threads will see same instance of
ThreadLocal, but a thread will be able to see value which was set by it only.
Q. How
thread set value of ThreadLocal >
threadLocal.set(
new Date().toString());
Thread set value of ThreadLocal by calling
set(“”) method on threadLocal.
How thread get value of ThreadLocal > threadLocal.get()
Thread get value of ThreadLocal by calling
get() method on threadLocal.
See here for detailed explanation of threadLocal.
Q. What is busy spin? What is busy spin?
A. When one thread loops continuously waiting
for another thread to signal.
Performance point of view - Busy spin is very
bad from performance point of view, because one thread keeps on looping
continuously ( and consumes CPU) waiting for another thread to signal.
Solution to busy spin -
We must use sleep () or wait()
and notify() method. Using wait() is better option.
Q. Why
using wait() and notify() is much better option to solve busy spin?
Because in case when we use sleep() method,
thread will wake up again and again after specified sleep time until boolean
variable is true. But, in case of wait() thread will wake up only when when
notified by calling notify() or notifyAll(), hence end up consuming CPU in
best possible manner.
Program - Consumer Producer problem with busy
spin >
Consumer thread continuously execute (busy
spin) in while loop tillproductionInProcess is true. Once producer thread has
ended it will make boolean variable productionInProcess false and busy spin
will be over.
while(productionInProcess){
System.out.println("BUSY SPIN - Consumer
waiting for production to get over");
}
Q. Can a constructor be synchronized?
A. No, constructor cannot be
synchronized. Because constructor is used for instantiating object, when we are
in constructor object is under creation. So, until object is not instantiated
it does not need any synchronization.
Enclosing constructor in synchronized block
will generate compilation error.
Using synchronized in constructor definition
will also show compilation error.
COMPILATION ERROR = Illegal modifier for the
constructor in type ConstructorSynchronizeTest; only public, protected &
private are permitted
Though we can use synchronized block inside
constructor.
Read More about : Constructor in java cannot be synchronized
Q. Can you find whether thread holds lock on
object or not?
Answer. holdsLock(object) method can be
used to find out whether current thread holds the lock on monitor of specified
object.
holdsLock(object) method returns true if the
current thread holds the lock on monitor of specified object.
Q. What do you mean by thread starvation?
Answer. When thread does not enough CPU
for its execution Thread starvation happens.
Thread starvation may happen in following
scenarios >
- Low
priority threads gets less CPU (time for execution) as compared to high
priority threads. Lower priority thread may starve away waiting to get
enough CPU to perform calculations.
- In deadlock two
threads waits for each other to release lock holded by them on resources.
There both Threads starves away to get CPU.
- Thread
might be waiting indefinitely for lock on object’s monitor (by
calling wait() method), because no other thread is calling notify()/notifAll() method
on object. In that case, Thread starves away to get CPU.
- Thread
might be waiting indefinitely for lock on object’s monitor (by calling
wait() method), but notify() may be repeatedly awakening some other
threads. In that case also Thread starves away to get CPU.
Q. What is addShutdownHook method in java?
Answer. addShutdownHook method in
java >
- addShutdownHook
method registers a new virtual-machine shutdown hook.
- A
shutdown hook is a initialized but unstarted thread.
- When
JVM starts its shutdown it will start all registered shutdown hooks in
some unspecified order and let them run concurrently.
When JVM (Java virtual machine) shuts
down >
- When
the last non-daemon thread finishes, or
- when
the System.exit is called.
Once JVM’s shutdown has begunnew shutdown
hook cannot be registered neither previously-registered hook can be
de-registered. Any attempt made to do any of these operations causes an
IllegalStateException.
Q. How you can handle uncaught runtime
exception generated in run method?
Answer. We can use setDefaultUncaughtExceptionHandler method
which can handle uncaught unchecked(runtime) exception generated in run()
method.
What is setDefaultUncaughtExceptionHandler
method?
setDefaultUncaughtExceptionHandler method
sets the default handler which is called when a thread terminates due to an
uncaught unchecked(runtime) exception.
setDefaultUncaughtExceptionHandler method
features >
- setDefaultUncaughtExceptionHandler
method sets the default handler which is called when a thread terminates
due to an uncaught unchecked(runtime) exception.
- setDefaultUncaughtExceptionHandler
is a static method method, so we can directly call
Thread.setDefaultUncaughtExceptionHandler to set the default handler
to handle uncaught unchecked(runtime) exception.
- It
avoids abrupt termination of thread caused by uncaught runtime exceptions.
Defining setDefaultUncaughtExceptionHandler
method >
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler(){
publicvoid uncaughtException(Thread thread,
Throwable throwable) {
System.out.println(thread.getName() + "
has thrown " + throwable);
}
});
Q. What is ThreadGroup in java, What is
default priority of newly created threadGroup, mention some important
ThreadGroup methods ?
Answer. When program starts JVM creates
a ThreadGroup named main. Unless specified, all newly created
threads become members of the main thread group.
ThreadGroup is initialized with default
priority of 10.
ThreadGroup important methods >
- getName()
- name
of ThreadGroup.
- activeGroupCount()
- count
of active groups in ThreadGroup.
- activeCount()
- count
of active threads in ThreadGroup.
- list()
- list()
method has prints ThreadGroups information
- getMaxPriority()
- Method
returns the maximum priority of ThreadGroup.
- setMaxPriority(int
pri)
- Sets
the maximum priority of ThreadGroup.
Q. What are thread priorities?
Thread Priority range is from 1 to 10.
Where 1 is minimum priority and 10 is maximum
priority.
Thread class provides variables of final
static int type for setting thread priority.
/* The
minimum priority that a thread can have. */
publicfinalstaticintMIN_PRIORITY= 1;
/* The default priority that is assigned to a
thread. */
publicfinalstaticintNORM_PRIORITY= 5;
/* The
maximum priority that a thread can have. */
publicfinalstaticintMAX_PRIORITY= 10;
Thread with MAX_PRIORITY is likely to get
more CPU as compared to low priority threads. But occasionally low priority
thread might get more CPU. Because thread scheduler schedules thread on
discretion of implementation and thread behaviour is totally unpredictable.
Thread with MIN_PRIORITY is likely to get
less CPU as compared to high priority threads. But occasionally high priority
thread might less CPU. Because thread scheduler schedules thread on discretion
of implementation and thread behaviour is totally unpredictable.
setPriority()method is used for Changing the
priority of thread.
getPriority()method returns the thread’s
priority.

Comments
Post a Comment