Synchronization in Java
Synchronization in Java
Java Synchronization is better option where we want to allow only one thread
to access the shared resource.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
1
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.
Class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100); } }
2
class TestSynchronization{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
3
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
4
Example of synchronized method by using
annonymous class
//Program of synchronized method by using annonymous class
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
public class TestSynchronization{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
5
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific
resource of the method.
Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work
same as the synchronized method.
6
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
7
Example of synchronized block by using annonymous
class:
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
public class TestSynchronizedBlock2{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
8
Inter-thread communication in Java
1. Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
o wait()
o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
2) notify() method
3) notifyAll() method
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
9
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
10
public void run(){c.deposit(10000);}
}.start();
}}
11
Implementing the Runnable Interface
The Runnable interface declares the run() method that is required for implementing
threads in our programs. TO do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from this “runnable”
class as the target of the thread.
4. Call the thread’s start() method to run the thread.
Eg:
class X implements Runnable
{
class DemoRunnable
{
12
Thread Runnable
13