Java Multithreading important terms – Theory aparts
Monitor -
it ensures that only one thread can enter in its critical section. It is associated with every object in java. Synchronized acquires a monitor for a thread. It is also called intrinsic or monitor lock.
method(
//some statement
synchronized(this){
//some statement
}
}
method2(
synchronized(this){
}
//Some statement
}
Starvation –
If there are multiple threads waiting on same object, notify() can awake any thread randomly. It arises the condition that some threads never get awaken and some always get awaken. This situation is called Starvation. Sometimes some greedy threads don’t release resources (call sleep() instead of wait() etc). It also force other threads to wait. Some threads increase their priority to get served first to CPU, it also force low priority threads to wait for long. These all conditions where any thread need to wait very long is called Starvation.
Slipped condition –
from the time a thread has checked a certain condition until it acts upon it, the condition has been changed by another thread.
method(
:
while(amount < required){
synchronized(filler){
filler.notify();
}
wait();
}
amount -= required;
:
}
Race condition -
Race conditions occur only if multiple resources are accessing the same resource, and one or more of the threads write to the resource. If multiple threads read the same resource race conditions do not occur.
DeadLock –
When all threads waiting outside the door closed by another thread. And this chain is either circular or ending on resource which cant be assigned to any thread due to some reasons. (Might be because it is held by some devil thread).
Nested Monitor Lockout –
Lock inside lock. wait() releases one of the lock but not all. It results deadlock.
method(
synchronized(this){
while(flag){
synchronized(a){
a.wait();
}
}
}
}
method2(
synchronized(this){
flag = false;
synchronized(a){
a.notify();
}
}
}
Guarded/loop/spin lock –
Loop & Wait until the condition becomes false.
while(condition){
wait();
}
Reentrance Lock –
When one thread calls a synchronized block inside from another synchronized block on the same object. (when a thread reenters in its monitor)
public synchronized outer(){
inner();
}
public synchronized inner(){
//do something
}
It is allowed for same thread. But if 2 separate threads access 2 separate synchronized blocks, then one of them will have to wait.
Daemon Thread –
A thread that has no other role in life than to serve others. For example Timer thread. JVP stop executing a program if only daemon. To make a thread daemon in java just call setDaemon(true) on a thread.
views


No Comments