Understanding Java Thread Synchronization with methods vs objects vs locks

Utkarsh
Utkarsh
Oct 10, 2020 · 4 min read

Imagine a case where we have two functions.

One increments the value of counter field and other decrements the value.
We want to use multithreading to achieve this.

OS will try to preempt and schedule two threads on its own for optimizations. So we cannot rely on order of execution of threads.

Problem

But there is a problem with above piece of code.

Problem 1 : We are using two threads to access the shared memory (CommonClass object = new CommonClass() allocates on heap and hence counter field is shared),
we face a problem here as we are uncertain about the value of counter.
It may happen the thread1 has increased the value twice while thread2 has decreased only once.

.

Problem 2 : We have non atomic operations here i.e this.counter++ is doing three things reading counter value, incrementing it and writing it.
So we may overwrite the work done by one threads or read an inconsistent value because thread context switch can happen at anytime.

So it is important to identify the piece of code where one of these problem can occur. We call them critical sections.

There are two major ways to solve the problem :

Solution 1 : Synchronize threads using synchronized keyword for method.

We know that incrementValue and decrementValue functions are critical sections here. They perform non atomic operations on shared piece of memory.
So we can use synchronized keyword for function. This will block a thread to enter critical sections (incrementValue & decrementValue) when other thread is inside it.

Answer 1

But how does it works ?
Both methods are indeed part of the same object(object) and the two synchronized blocks (incrementValue and decrementValue)
synchronize on same object (
‘this’ object).

Can we do better?
Yes instead of synchronizing the whole method, we can synchronize just the critical section using external locks.

.

Solution 2 : Synchronize threads using external locks

We can create a object( any object) and use it as external lock.
Here we can use synchronized keyword for lock.
This will block a thread to enter critical sections (incrementValue & decrementValue) when other thread is inside it.

Answer 2

But how does it works ?
Both methods are indeed part of the same object(object) and the two synchronized blocks synchronize on same object (lock).
Even synchronized keyword for method is nothing but a synchronized on
‘this’ object of class.

Lets compare the two solution to each other in the samples given below.

.

.

.

Sample 1
public synchronized void incrementValue() {
this.counter++;
}

Sample 2
public void incrementValue() {
synchronized (this) {this.counter++;}
}

Solution 3 : Synchronize threads using different locks

We can synchronize threads using different locks.
Imagine two counters (counter1 and counter2) and we want to increase one and decrease other.
We can use multithreading here to do them concurrently or in parallel.

We are using two threads to access the shared memory (CommonClass object = new CommonClass() allocates on heap )
We can use two locks for two sections.

Answer 3

But how does it works?
Both methods are indeed part of the same object (object), however the two synchronized blocks (incrementValueCounter1 & decrementValueCounter2),
synchronize on different objects(
lock1 and lock2) and hence won’t affect each other.

In fact in this case we don’t even need locks or multithreading.

.

.

Solution 4 : Synchronize threads for different objects

We are using two threads to access the non shared memory on heap.
object1 and object2 are independent on heap.

Answer 4

But how does it works?
The method is indeed part of the different objects (object1 and object2) so the synchronized block (incrementValue for both objects),
synchronize on different objects(
‘this’ for object1 and ‘this’ for object2) and hence won’t affect each other.

In fact in this case we don’t even need locks.

Follow this series for more articles on Multithreading, Concurrency & Parallel programming in Java

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Utkarsh

Written by

Utkarsh

https://uvasistha.github.io/Portfolio/

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store