Write about SYNCHRONIZATION in Java?


SYNCHRONIZATION:

Threads that use their own data and methods provided  inside their run( ) methods. What happens when they try to use data and methods outside themselves  on such occasions, They may compete  for the same reasons and may lead to serious problems. For example, One thread may try to read a record from a file while another in still writing to the same file. Depending on the situation, We may get  storage results ,Java enables us to overcome this problem using a technique known as synchronization.

The keyword synchronized helps to solve such problems by keeping a watch on such locations.
Definition:

When a thread is acting on an object preventing any other thread from acting on the same object is called synchronization of threads. This  is also called thread safe. The synchronization concept is called locked object. If more than one thread is acting on the same object the results will not be reliable. In multi threading we must synchronize the threads in multi threading.

Two ways are there for thread synchronization. We can  synchronize  block of statements using synchronized block.

   synchronized    ( lock-object)
    {
    -----------
    -----------
    }

We can synchronize an entire method by writing synchronized keyword before a method.

synchronized void update( )
{
  -----------
 ------------
}

We declare a method synchronized, Java creates a monitor and handles it to the thread, that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock.

Whenever a thread has completed in work of using synchronized method (or block of code),It will hand our monitor to the next thread that is ready top use the same resource.

DEADLOCK:

When a thread wants to act on the object which has been already locked by another thread, and the second thread wants to act on the first object which is locked by the first thread, then both the threads will be in waiting state , forever.This is called dead lock of threads.

deadlock


In thread dead lock the program halts for any further process is suspended.

Thread A:

synchronized method2( )
{
synchronized method1( )
{

}
}

Thread B:

Synchronized method1( )
{
Synchronized method2( )
{

}
}

Related

Java 1412989310048388858

Post a Comment

emo-but-icon

item