Understanding Java Thread Synchronization with methods vs objects vs locks

Understanding Java Thread Synchronization with methods vs objects vs locks

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

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.

Image for post

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.

multithreading concurrency programming threads java

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Java Multithreading Example | Multithreading in Java

Java Multithreading Tutorial With Example | Multithreading in Java. Multithreading is a process of executing multiple threads simultaneously.

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

Java Concurrency: Thread Life Cycle

In this article, we’ll discuss in detail a core concept in Java — the lifecycle of a thread. In the Java language, multithreading is driven by the core concept of a Thread. During their lifecycle, threads go through various stages.

6 Best Books to Learn Multithreading and Concurrency in Java

These are the best books to learn multi-threading and concurrency in Java for both beginners and experienced Java programmers and developers.

Java | Multithreading

Multithreading is a process of concurrent execution of two or more parts of a program, for maximum utilization of CPU.