Introduction
In this article, we are going to discuss synchronization in Java. Now we are only discussing where and how we use a Synchronized block in Java. You can also achieve synchronization using a synchronized method. It's very easy; just use the synchronized keyword in front of the method and then your method is synchronized.
What is Synchronization?
Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to an error.
Synchronized block in Java
In Java, a synchronized block is another way to execute code synchronized. The block is provided an object to allow execution of a block of code to be synchronized on the lock of this object.
Syntax
synchronized(this)
{
//write here your code
}
Why use Synchronization?
When multiple threads access the same data item (resource) and more than one thread wants to change the resources then it can happen that two threads change the resource simultaneously which can corrupt the data. Suppose one thread increments a data item and another thread decrements the same data item; this may cause data corruption. So that is why we use synchronization.
Note:
Every Java object created, including every Class loaded, has an associated lock or monitor. Putting code inside a synchronized block makes the compiler append instructions to acquire the lock on the specified object before executing the code, and release it afterwards (either because the code finishes normally or abnormally). Between acquiring the lock and releasing it, a thread is said to "own" the lock. At the point the thread wants to acquire the lock, if another thread already owns it, then the thread attempting to get a lock must wait for the other thread to release it.
Example
- package ab;
- class Callme
- {
- void call(String msg)
- {
- System.out.print("[" + msg);
- try
- {
- Thread.sleep(2000);
- } catch (InterruptedException e)
- {
- System.out.println("Interrupted");
- }
- System.out.println("]");
- }
- }
- class Caller implements Runnable
- {
- String msg;
- Callme target;
- Thread t;
- public Caller(Callme targ, String s)
- {
- target = targ;
- msg = s;
- t = new Thread(this);
- t.start();
- }
- public void run()
- {
- synchronized(target)
- {
-
- target.call(msg);
- }
- }
- }
- class Synch1
- {
- public static void main(String args[])
- {
- Callme target = new Callme();
- Caller ob1 = new Caller(target, "abhishek");
- Caller ob2 = new Caller(target, "Synchronized");
- Caller ob3 = new Caller(target, "Dubey");
- Caller ob4 = new Caller(target, "MCA");
- Caller ob5 = new Caller(target, "2012 batch");
- try
- {
- ob1.t.join();
- ob2.t.join();
- ob3.t.join();
- ob4.t.join();
- ob5.t.join();
- } catch (InterruptedException e)
- {
- System.out.println("Interrupted");
- }
- }
- }
Output