Synchronization & its types

Synchronization 
  • Synchronization in java is the capability to control the access of multiple threads to any shared resource.
  • Threads communicate primarily by sharing access to fields and the objects.
  • This form of communication is extremely efficient, but makes two kinds of errors possible: 
    • thread interference and memory consistency errors. 
  • The tool needed to prevent these errors is called synchronization.
  • However, synchronization can introduce thread contention, which occurs when two or more threads try to access the same resource simultaneously and cause the Java run time to execute one or more threads more slowly, or even suspend their execution.

  • Synchronization in java is the capability to control the access of multiple threads to any shared resource.
  • Synchronization in Java is possible by using Java keywords "synchronized" and "volatile”.
  • Java synchronized code will only be executed by one thread at a time.
  • Synchronization is possible in JAVA with three types of ways.
    • Using Synchronization method 
    • Using Synchronization blocks
    • Using Static Synchronization 
Thread Interference
  • Interference happens when two operations, running in different threads, but acting on the same data, interleave. 
  • This means that the two operations consist of multiple steps, and the sequences of steps overlap.
  • Example:
    • Suppose Thread A invokes increment at about the same time Thread B invokes decrements. 
    • If the initial value of c is 0, their interleaved actions might follow this sequence:
    • Thread A: Retrieve c.
    • Thread B: Retrieve c.
    • Thread A: Increment retrieved value; result is 1.
    • Thread B: Decrements retrieved value; result is -1.
    • Thread A: Store result in c; c is now 1.
    • Thread B: Store result in c; c is now -1.
  • Thread A's result is lost, overwritten by Thread B. 
Memory Consistency Errors
  • Memory consistency errors occur when different threads have inconsistent views of what should be the same data. 
  • The key to avoiding memory consistency errors is understanding the happens-before relationship.
  • Example:
    • Suppose a simple int field is defined and initialized: int counter = 0;
    • The counter field is shared between two threads, A and B. 
    • Suppose thread A increments counter: counter++; 
    • Then, shortly afterwards, thread B prints out counter: System.out.println(counter);
    • If the two statements had been executed in the same thread, it would be safe to assume that the value printed out would be "1". 
    • But if the two statements are executed in separate threads, the value printed out might well be "0"
Using Synchronization method
  • Note: that constructors cannot be synchronized.
    • Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.
    • Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: 
  • If an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
  • Example:
  • Synchronization use an internal entity known as the intrinsic lock or monitor lock. 
  • Why Intrinsic locks in synchronization? 
    • Allow to access objects state
    • Establishing happens-before relationships
  • Every object has an intrinsic lock associated with it. 
  • A thread access the objects’ fields, we need apply intrinsic lock and release intrinsic lock when work done.
  • A thread is said to own the intrinsic lock between the time it has apply the lock and released the lock. 
  • As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. 
  • The other thread will block when it attempts to acquire the lock.
  • When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.
  • Synchronized block can be used to perform synchronization on any specific resource of the method.
  • Example: 
    • 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.
  • Example:
  • Points to remember for Synchronized block
    • Synchronized block is used to lock an object for any shared resource.
    • Scope of synchronized block is smaller than the method.
  • Recall that a thread cannot acquire a lock owned by another thread. 
  • But a thread can acquire a lock that it already owns
  • Allowing a thread to acquire the same lock more than once enables reentrant synchronization. 
  • This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. 
  • Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

1 Comments

Thanks a lot for query or your valuable suggestions related to the topic.

  1. ==> This Program is for printing a table of a given number using synchronized block.
    ==> using a Separate Input Dialog Box.
    ==> TRY.. PASTE.. and IMPLEMENT it..!!!!
    ==> By Piyush Ramchandani {MCA department - GNU}

    package threadexample3;

    import javax.swing.JOptionPane;

    public class ThreadExample3 extends Thread{

    public void run(){
    synchronized(this)
    {
    int n = Integer.parseInt(JOptionPane.showInputDialog("Enter any Number"));
    for (int i = 1; i <= 10; i++) {
    System.out.println(n + "*" + i + "=" + n * i);
    }
    }
    System.out.println("\n Eno:2060 - Piyush Ramchandani");
    }
    public static void main(String[] args) {
    ThreadExample3 t1 = new ThreadExample3();
    t1.start();
    }
    }

    ReplyDelete
Previous Post Next Post

Contact Form