Member-only story

Java Multithreading, Concurrency, and Parallelism — Part 7

KRISHNA KISHORE V
7 min readDec 8, 2021

--

Synchronizing the Threads with synchronized

NOTE: Please follow the content till the end as I tried to explain the things at the bytecode level.

In part-6 we have seen the methods join, sleep, and yield with their behaviors. Now it is time to look at how the threads can be synchronized to access the shared data. In Java, shared data simply means another object that contains some data for the threads to function: For example the instance of type Counter.

But in the first place why there is a need for synchronizing the threads to access the object - the Shared Data.

Let’s imagine a common scenario of displaying the number of hits of a particular website on the UI. The backend servers need to maintain a counter that keeps track of the number of hits. And for every request, there is a request handler that runs in a specific thread that needs to access the counter object and call increment on it.

Let's look at the below example where we have two threads, accessing the same Counter object. Each thread is incrementing the counter 100000 times. At the end of both threads completing their execution, the expected output should be 200000 because each thread performs 100000 increments.

--

--

KRISHNA KISHORE V
KRISHNA KISHORE V

Written by KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer

No responses yet

Write a response