Showing posts with label synchronization works in java. Show all posts
Showing posts with label synchronization works in java. Show all posts

How synchronization works in java | synchorization working concept | point to remember during java synchronization interview question

Java Synchronization concept :

Every object has a intrinsic lock or monitor lock or simply we can say monitor . A thread can enter a sychronized method only if the thread can aquire the Object's lock. Once the thread aquires the lock automatically for a synchronized method , the thread enters into that method . As only one thread can own a lock of the object at a time, no other thread can own the same lock and enter into same synchronized method and other synchronized methods in the same object. The lock is released when the thread exits the synchronized method. The lock release occurs even if the return was caused by an uncaught exception. Now other thread can acquire the same lock to execute other synchronized methods or same method. When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock to ensure the reliable communication between threads.

There are two ways in which you can use synchronization to manage your threads of execution.
1. Synchronizing methods - Managing code at the method level .
eg. public synchronized void withdraw(int amount)
{code in method.}
2. Synchronizing statements(block of code) -Managing code at the block level.
eg. synchronized (object/class) { block of code }

Synchronized Methods

For protecting shared data / resource , no need to lock the data itself, we need to synchronize the methods that access that data / resource. You can make methods of a class mutual exclusive by declaring them using the keyword synchronized . You can make all the methods or some of the methods of a class synchronized depending upon the requirements. You have to synchronize those methods only that access / modify the shared data (eg. instance variables) or resources. All reads or writes to that object's variables by a thread are visible to other threads through synchronized methods.

Consider the above sample code for bank account.

class Account
{
private int balance;
private int accountNumber;
.........
public synchronized int getBalance()
{ return balance;
}

public synchronized void withdraw(int amount)
{
........
if (balance<amount)
{
throw new RuntimeException("Amount not available");
} balance -= amount;}

public void method3()
{
// code for the method3
}
}

 The above account class has three methods . Both withdraw() and getBalance() are synchronized and method3 is not synchronized. Now only one of the synchronized methods in a class object can execute at any one time . That means either withdraw() method or getBalance() method can be executed at any one time . method3 can always be executed by a thread. Unnecessary syncronization may reduce the performance of the program

Synchronizing Statement(s) (Blocks of code)

You can synchronize a statement or a block of code without synchronizing the whole method using the syntax given below . Synchronized statements must specify the object that provides the intrinsic lock. This is more useful because you can specify particular object that benefits from synchronization of the staments . When a thread enters the block that is synchronized on any given object , no other thread can enter other synchronized blocks or methods on the same object . Syntax is
synchronized(obj)
 {
 Block of code
 }

List list = Collections.synchronizedList(new ArrayList());
The above line returns a thread-safe list backed by the specified list . If one thread changes the list while another thread is traversing it through an Iterator, it will throw ConcurrentModificationException. To stop this exceptioin, Lock the entire List when you are iterating by using the synchronized block that synchronizes on the the returned list .
//block of code synchronized on list. So when the list is modified , it can't be traversed. When the list is iterated , this list can't be modified.

 synchronized(list) {
 Iterator iter = list.iterator();
while (iter.hasNext())
 doSomething(iter.next());
 }

You can also use , private lock object that is inaccessible outside, with synchronized block instead of using synchronized methods
private final Object lock1 = new Object();
 public void inc1() {
 synchronized(lock1) {
 c1++;
 }
 }

Synchronization can be considered expensive , because

1. Synchronization leads to poor performance.
a) The JVM takes time to make ordering of synchronization actions executing in different threads.
b) When a thread enters synchronized method, it has to acquire object's lock and releases when exits the method.
c) JMM (Java Memory Model) requires that the cached values to be invalidated immediately after the lock is acquired, and writing cache values back to main memory (flushing the cache) before it is released which ensures the proper inter-thread communication . Flushing the cache frequently can be expensive
2. Synchronized method can slow down the program execution , because synchronization does not allow concurrency . Only one thread is allowed at a time to enter into synchronized methods.
3. Synchronized methods may lead to deadlock

Summary points to remember on synchronization for Interview


1. The main objective of synchronization is to ensure that when several threads want access to a single resource , only one thread can access it at any given time.
2. Each object has only one lock.
3. Instance method gets lock on the Object where as static method get locks the Class in which the method is defined
4. Final fields and Immutable objects are thread-safe that requires no synchronization.
5. Constructors cannot be synchronized
6. If an object is visible to more than one thread, all reads or writes to that object's variables need to be done through synchronized methods.
6. Reentrant Synchronization : A thread can acquire a lock that it already owns which helps to invoke a method that also contains synchronized code
7. Alternative ways of synchronization are the use of classes in the java.util.concurrent package , declaring volatile variables that ensures all threads see a consistent value for the variable
8. The volatile modifier helps for reliable communication between threads but does not suuport for mutual exclusion
9. wait() method of object that can be called from synchronized methods or synchronized block to give up the lock i.e. to suspend the current thread until the notify() or notifyAll() method is called.

Complete program to test with synchronization and without Synchronization

import java.util.Random;
class Account {
private int balance;
private int accountNumber;
public Account(int accountNumber, int balance)
{
this.accountNumber=accountNumber;
this.balance=balance;
}
public synchronized int getBalance()
{
return balance;
}

public synchronized void withdraw(int amount) {
System.out.println("Accout Number = " + accountNumber + " " + Thread.currentThread().getName() + " needs " + amount);
try
{
Thread.sleep(30);
}catch(Exception e){ }

if (balance<amount)
{
System.out.println("Available Balance is = " + balance + " which is less than required amount " + amount);
throw new RuntimeException("Amount not available");
}
balance -= amount;
System.out.println(Thread.currentThread().getName() + " Withdraws " + amount );
System.out.println( " Current balance = " + balance);
}
}

public class BankOperation1 implements Runnable {
private Account account = new Account(21120, 10000);
public static void main (String [] args) {
BankOperation1 wd = new BankOperation1();
Thread person1 = new Thread (wd) ;
Thread person2 = new Thread (wd) ;
person1.setName ("Johnson") ;
person2.setName ("Jacob") ;
person2.start () ;
person1.start () ;
}
public void run ( ) {
Random rndObj = new Random();
System.out.println("Available Balance= " + account.getBalance());
//for (int i= 1; i <= 100; i++)
//{
account.withdraw(7500) ;
//}
}
}


When I run the above code without synchronized methods , i got the below output rarely. Remove synchronized keyword from the above code for testing


The above output shows , both threads (Mr. Jacob & Mr. Jhonson) enters into withdraw () method . Both withdraws money Rs. 7500/- . and the changes made to balance variable by one thread are not communicated to other thread.

When I run the above code with synchronized methods, i got the below output every time


The above output shows , only one thread (either Mr. Jacob or Mr. Jhonson) enters into withdraw () method . The first thread is able to withdraw money Rs. 7500/- . and the changes made to balance variable by one thread is communicated to other thread.