A)
->in java, synchronization is implemented by using the modifier “synchronized”. We have two levels of synchronization.
1) method level
2) block level
->if we apply synchronized modifier to the method of an object, it is known as method level synchronization.
Ex:
Synchronized void withdraw(0 // method level synchronization
Synchronized void withdraw(0 // method level synchronization
{
---
---
}
->when there is no source code available with us we can’t ass synchronized to that method.
->therefore at method level w can’t do.
->Therefore go for process level.
Class acccountthread
{
run()
{
Synchronized(acc)
{
acc.withdraw();
}
}
}
->instead of declining the method as synchronized, we can create a block of statements by using “Synchronized” modifier. It is known as block level synchronization.
->Synchronized block has the fallowing syntax:
Synchronized(object)
{
// block of statements.
}
Ex:
public void run()
{
Synchronized(acc)
{
acc.withdraw();
acc.withdraw();
}
}
Ex:
Public void withdraw(float amt)
{
---
---
Synchronized(this)
{
//vital code that should not be executed parllelly by more than one thread on the same
//object.
}
----
----
}
->in the first example we may or may not have the source code.
->second example is mostly used.
->when acc object one same, stop parallelism that is when x threads are acting on same object.
Public void run()
{
acc.withdraw();
}//error
->here there may be a chance of data inconsistency in previous program code. So use synchronized.
->method level synchronization on is not powerful.
->block level Synchronization is powerful.
->2nd example written only if we know withdrawn. i.e. developed by us.
Therefore synchronized block causes serial processing which reduces performance.
Therefore keep only less code in synchronized block.
->EJB container provides multithreading code to program implicitly.
->web container provides multithreading code to servlets, JSP.
->synchronization is the background uses the concept of mutex (mutually exclusive block), monitor.
->in the background synchronized keyword is given to JVM. JVM gives to os. Os implements this mutex, monitor.
->monitor:
Critical reason of code is created by os.
Critical reason of code is created by os.
Where only one thread is allowed at a time to access (all synchronized methods of that
object is monitor size. The code that is kept in monitor can’t be parllelly executed).
->mutex:
Only one of threads, will get lock, all will not get lock. Other threads can’t enter
monitor. When lock is released, i.e. executes the code only then it can enter monitor.
Comments
Post a Comment