Synchronization & Lock in Java Threads

Thanoshan MV
2 min readJul 27, 2020
Photo by Everton Vila on Unsplash

Threads share memory and resources (data, code etc.) Threads execute concurrently. Hence, threads can access common resources simultaneously. This may bring us some undesirable outcome.

Synchronization prevents threads from accessing common resources simultaneously. It allows a thread to access a resource at a time.

Each object has a lock. If one thread has gained that object’s lock, the other threads will have to wait until that particular thread releases it. In this way, a thread can access a resource at a time.

We can use synchronized non access modifier to gain object’s lock. This modifier can be applied to methods and blocks.

1. Methods

/**
* synchronized instance method
*/
public synchronized void method(){

}

Static methods can also be synchronized.

/**
* synchronized static method
*/
public static synchronized void method(){
}

2. Blocks

Synchronized blocks should have common resource object as an argument.

synchronized(object){
}

Let’s say we need to define synchronized blocks in our common resource object’s class, we need to provide this class’ object as an argument to that block:

/**
* blocks inside instance methods
*/
public void instanceMethod() {
synchronized(this) { }
}
/**
* blocks inside static methods
*/
public static void staticMethod() {
synchronized(className.class) { }
}

For synchronization:

  1. We should have synchronized methods or synchronized blocks.
  2. We should have only one common resource object.

So, only one thread executes a method at a time. Other threads will wait until the previous thread finishes its method call (methods refer to synchronized methods and methods that contain synchronized blocks).

NOTE: A class can have synchronized and non synchronized methods.

NOTE: Even if a thread is in sleep, it will have the object’s lock. It will not release it.

While one thread is accessing to the synchronized code, the other threads can access non synchronized code.

--

--