---
title: "Explain with example to handle synchronization in Java."  
description: "Explain with example to handle synchronization in Java."  
author: "Revati S Misra"  
published: 2024-07-19  
updated: 2024-07-19  
canonical: https://www.mindstick.com/forum/160964/explain-with-example-to-handle-synchronization-in-java  
category: "java"  
tags: ["java", "synchronization", "programming language"]  
reading_time: 4 minutes  

---

# Explain with example to handle synchronization in Java.

Explain with example to [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) [synchronization](https://www.mindstick.com/articles/11983/synchronization-in-c-sharp) in Java.

## Replies

### Reply by Ashutosh Patel

#### Synchronization in Java

Synchronization is used to control access to shared resources between multiple threads to prevent concurrent access that can cause inconsistent or corrupted data If multiple threads access a shared resource at the same time in which synchronization ensures that only one thread can synchronize a piece of code or a method at a time.

#### Synchronization Using `synchronized` Keyword

## Synchronized Method

```java
public class Program {
   private int count;
   public synchronized void increment() {
       count++;
   }
   public synchronized int getCount() {
       return count;
   }

   public static void main(String[] arg)
   {
       Program prog = new Program();
       prog.increment();
       System.out.println(prog.getCount());
   }
}
```

The `increment()` and `getCount()` methods are marked as synchronized, which means that only one thread can execute either of these methods on the same instance of Counter at any given time.

## Synchronized Block

```java
public class BankAccount {
   private double balance;
   public void deposit(double amount) {
       synchronized (this) {
           balance += amount;
       }
   }
   public void withdraw(double amount) {
       synchronized (this) {
           if (balance >= amount) {
               balance -= amount;
           }
       }
   }
   public double getBalance() {
       synchronized (this) {
           return balance;
       }
   }
}
```

## In the example above,

- The `synchronized (this)` block is used inside methods to synchronize access to the balance variable.
- Each synchronized block ensures that only one thread at a time can execute the code within the block, preventing concurrent access issues.
- It is important to note that using `synchronized(this)` locks the current instance of the class `(this)`, which means other threads cannot execute synchronized blocks of the same instance simultaneously.

#### Key Points to Remember

**Locking Mechanism-** Synchronization in Java is implemented by an internal locking mechanism associated with each object. When a thread enters a synchronized method or block, it acquires a lock on the object, while other threads wait until the lock is released.

**Scope-** Synchronization can be applied at the method level (`synchronized` method) or within specific blocks (`synchronized (object)`).

**Performance Considerations-** Although synchronization ensures thread safety, it can affect performance due to thread contention (threads waiting for lock). Use synchronization only where necessary and consider options such as `java.util.concurrent` package classes for more fine control and performance improvements.

## Example-

```java
class Counter {
   private int count;
   public synchronized void increment() {
       count++;
   }
   public synchronized int getCount() {
       return count;
   }
}
public class Program {
   public static void main(String[] args) {
       Counter counter = new Counter();
       // Creating multiple threads to increment the counter
       Thread thread1 = new Thread(() -> {
           for (int i = 0; i < 1000; i++) {
               counter.increment();
           }
       });
       Thread thread2 = new Thread(() -> {
           for (int i = 0; i < 1000; i++) {
               counter.increment();
           }
       });
       // Start the threads
       thread1.start();
       thread2.start();
       // Wait for threads to complete
       try {
           thread1.join();
           thread2.join();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       // Print the final count
       System.out.println("Final Count: " + counter.getCount());
   }
}
```

\
**Explanation**

- The `Counter` class has a synchronized `increment()` method.
- The `main` class consists of two threads (`thread1` and `thread2`) that increment the `Counter` at the same time.
- The `join()` method ensures that the main thread waits for `thread1` and `thread2` to finish before publishing the final count.
- Without synchronization, the final figure may not always be `2000`, but that synchronization ensures that it is correct in concurrent situations.

Synchronization in Java ensures thread safety by simultaneous changes to multiple threads of shared data. It is a basic concept of multithreaded programming in order to maintain consistency and avoid race conditions.

**Also, Read:** [Explain the concept of functional interfaces with examples in Java.](https://www.mindstick.com/forum/160965/explain-the-concept-of-functional-interfaces-with-examples-in-java)


---

Original Source: https://www.mindstick.com/forum/160964/explain-with-example-to-handle-synchronization-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
