Thread Synchronization in Java

Vijay BelwalVijay Belwal
2 min read

Thread synchronization ensures safe access to shared resources in concurrent programming. It eliminates issues like race conditions and data inconsistency by controlling how threads interact with critical sections of code.

✨ What is a Critical Section?

A critical section is a part of code that accesses shared resources and must not be executed by more than one thread at a time.

✅ Example:

Here, count++ is a critical section. If accessed simultaneously by multiple threads, it may lead to inconsistent results.

🧠 How to Identify a Critical Section

✅ Critical Section:

  • Code that reads/writes shared variables that can be modified by multiple threads.

  • Accessing or modifying shared collections, files, or databases.

  • Any code block that performs read-modify-write operations on shared resources.

❌ Not a Critical Section:

  • Operations on thread-local variables.

  • Pure computation not dependent on shared state.

  • Immutable or read-only shared data.

⚖️ Thread Synchronization

Thread synchronization ensures that only one thread can execute a critical section at a time.

Problems it prevents:

  • ❌ Data Corruption

  • ❌ Race Conditions

  • ✅ Ensures Thread Safety

🔐 Synchronized Keyword

1) Synchronized Method

  • For non-static methods: lock is acquired on the object instance.

  • For static methods: lock is acquired on the class object.

2) Synchronized Block

More efficient when only part of the method needs synchronization.

⚡ Volatile Keyword

volatile ensures that updates to a variable are always visible to all threads.

Guarantees:

  1. Visibility: Updates are visible across threads immediately.

  2. Ordering: Prevents instruction reordering around volatile variables.

When to use:

  • Flags

  • Status indicators

  • When atomicity isn't needed, just visibility

⚖️ Atomic Variables

Java provides atomic classes under java.util.concurrent.atomic for lock-free thread-safe operations on single variables.

When to use:

  • For counters or accumulators

  • Where locking is costly

  • For performance-critical applications

🔍 Summary

MechanismGuaranteesUse-case
synchronizedAtomicity + VisibilityShared critical sections
volatileVisibility onlyFlags, status indicators
atomic variablesLock-free atomic opsPerformance-critical counters etc.

Thread synchronization is crucial in multithreaded Java applications. Choose the right tool (synchronized, volatile, or atomic) depending on your use-case to ensure safety, performance, and correctness.

0
Subscribe to my newsletter

Read articles from Vijay Belwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vijay Belwal
Vijay Belwal