July 06, 2011

Synchronization techniques

Java provides two basic Synchronization techniques :


The main diffrence between Method and Block is - A Block gets executed when the control comes to it. But a Method gets executed when we are calling that Method only. Without method call a Method can't be executed, we have to call that Method explictily then only it gets executed.

1. Synchronized Methods

2. Synchronized blocks 

Synchronized Method : A Method declared with the synchronized keyword is called Synchronized Method

- To make a method Synchronized, simply add the synchronized keyword to its declaration.

There are two befits with the Synchronized Method :

First : It is not possible for two invocations of Synchronized Methods on the same Object to interleave. When one Thread is executing a Synchronized Method for an Object, all otherThreads that invoke Synchronized Methods for the same Object block (suspend execution) until the first Thread is done with the Object.

Second : When a Synchronized Method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a Synchronized Method for the same Object. This guarantees that changes to the state of the Object are visible to all Threads. 

Example : 

Code:
public class SynchronizedCounter {
        private int c = 0;

        public synchronized void increment() {
            c++;
        }

        public synchronized void decrement() {
            c--;
        }

        public synchronized int value() {
            return c;
        }
    }
Synchronized Block : A block of code declared with the synchronized keyword is called Synchronized Block

- To make a block of statements Synchronized, simply add the synchronized keyword to its declaration.

Example : 

Code:
public class SynchronizedCounter {
        private int c = 0;

        public synchronized 
         {
            c++;
          }
    }
Note : 
synchronize(this){}-this will get the lock of invoking object
synchrinize(any object referance)-this will get the lock of other object

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts