Java Threads

Easy Java Threads Tutorial – part 2 – Synchronization

Java Threads Tutorial Part 2 – Synchronization
When we have more than one thread that access the same resource its possible of them to access and change it at the same time and that will lead to errors – two types of errors are possible – thread interference errors and memory consistency errors. To avoid such scenario we need thread synchronization.

Introduction to Java Synchronization

In Java you have an option to choose from two basic synchronization types – synchronized methods and synchronized statements.

Synchronized methods

To make a method synchronized you only need to add the keyword synchronized to its declaration:

public synchronized void someMethod()

When one thread is executing a synchronized method of an object, all other methods that call synchronized methods of the same object suspend their execution until the first one is done with the synchronized method.
Synchronized method example

public class SyncSum
{
  private int sum = 0;
  public synchronized void add(int a) {
    sum += a;    
  }
  public synchronized void sub(int a) {
    sum -= a;
  }
  public synchronized void printSum() {
    System.out.print(sum);
  }
}

Synchronized Statements

You can create synchronized block of code through the synchronized statement. In synchronized statement you must specify the object that provides the intrinsic lock. You will learn more about intrinsic lock in the next part.

public void someMethod(int i) {    
    synchronized(this) {
        counter += i;
    }
}

What is intrinsic lock?

Intrinsic lock or monitor lock is an internal entity used in Java synchronization. The intrinsic lock enforces exclusive access to an object state and establish happens-before relationships. Every object has such monitor associated with it. The thread must acquire the monitor lock of an object before accessing the object and release it when its done with it. Its said that the thread owns the lock between the time it acquires it and the time the thread releases it. When a thread owns the monitor lock, no other thread can acquire the same lock.

What is reentrant synchronization?

Reentrant synchronization is when a thread acquires a lock that is already its own – for example when synchronized code calls a method that also contains synchronized code with the same lock. Without it in this situation the thread will block.

What are volatile variables?

Volatile is a keyword used to mark a variable that is stored in main memory and not in CPU cache. Each change is visible across the threads and the threads work with the variable at the main memory and do not copy it to CPU cache. It guarantees a happens-before relation.

What is deadlock?

Sounds cool right? But its not. Its a situation where two or more threads are blocked, waiting for each other.

Leave a Reply

Your email address will not be published. Required fields are marked *