Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Tuesday, 23 July 2013

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.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...