Java
Thread Safety
Synchronized Blocks
Concurrency
Multithreading

Thread-safe class in Java by means of synchronized blocks

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Thread Safety in Java Using Synchronized Blocks

Thread safety is a crucial concept in concurrent programming. In Java, it's often necessary to coordinate access to shared resources to prevent data corruption and ensure consistency. One of the primary constructs Java provides for achieving thread safety is synchronized blocks. This article explores what synchronized blocks are, how they work, and how they can be used to make a class thread-safe.

What is a Synchronized Block?

A synchronized block in Java is a way to ensure that multiple threads can safely access a shared resource without interference. It uses a lock, also known as a monitor, associated with an object. Only one thread at a time can execute a synchronized block of code protected by a specific monitor lock.

Syntax and Basic Usage

A synchronized block is typically defined using the following syntax:

  • `lockObject` is the object reference on which the synchronized block is locked. Before executing the block, the thread must acquire the lock on this object.
  • The critical section contains the code that should be executed in a thread-safe manner.
  • We use a private final object `lock` for synchronization. This pattern often ensures that the only way to reach the critical section is through code controlled by the class itself.
  • The `increment` and `getCount` methods are guarded by synchronized blocks, ensuring one thread at a time can modify or access the count variable.
  • Overhead: Synchronization introduces performance overhead, as acquiring and releasing locks is not free.
  • Deadlocks: Care must be taken to avoid deadlocks, a condition where two or more threads are blocked forever, each waiting to acquire locks held by each other.
  • Starvation and Fairness: There is no guarantee of fairness with synchronized blocks. A thread could starve if other threads continuously acquire the lock first.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.