0% found this document useful (0 votes)
71 views7 pages

Synchronized Block Vs Synchronized Method

The document compares synchronized methods and synchronized blocks in Java for managing thread safety. Synchronized methods lock the entire method, ensuring only one thread can execute it at a time, while synchronized blocks allow locking of specific code sections, improving concurrency. It emphasizes the importance of synchronization to prevent race conditions when multiple threads access shared resources, and discusses the advantages and drawbacks of each approach.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views7 pages

Synchronized Block Vs Synchronized Method

The document compares synchronized methods and synchronized blocks in Java for managing thread safety. Synchronized methods lock the entire method, ensuring only one thread can execute it at a time, while synchronized blocks allow locking of specific code sections, improving concurrency. It emphasizes the importance of synchronization to prevent race conditions when multiple threads access shared resources, and discusses the advantages and drawbacks of each approach.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Synchronized Block vs Synchronized Method

1. Synchronized Method
When you use the synchronized keyword in a method declaration, it locks the entire method, meaning only one thread can execute that
method on a particular instance of the class at any given time.

How it works:
• When a thread calls a synchronized method, it locks the object (or the class if the method is static) until the method completes.
• This ensures thread safety but may reduce concurrency since the entire method is locked, even if only part of the method
actually requires synchronization.
When to use:
• Use a synchronized method when you need to lock the entire method to ensure that only one thread accesses it at a time, especially
if all code within the method works with shared resources.

Example
This example simulates a scenario where multiple threads are trying to update a shared resource, like a bank account balance. Using a
synchronized method ensures that only one thread can access the critical section at a time
package com.example.demo.threads;

class BankAccount {
private int balance = 1000; // Shared resource

// Synchronized method to deposit money


public synchronized void deposit(int amount) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " is trying to deposit: " + amount);
Thread.sleep(5000);

balance += amount;
System.out.println(Thread.currentThread().getName() + " completed deposit. New balance: " + balance);
}

// Synchronized method to withdraw money


public synchronized void withdraw(int amount) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " is trying to withdraw: " + amount);
Thread.sleep(5000);
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " completed withdrawal. New balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " failed to withdraw due to insufficient balance.");
}
}

// Method to check balance (not synchronized)


public int getBalance() {
return balance;
}
}
public class SynchronizedMethodExample {
public static void main(String[] args) {

BankAccount account = new BankAccount(); // Shared resource

// Thread 1: Depositing money


Thread t1 = new Thread(() -> {
try {
account.deposit(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}, "Thread-1");

// Thread 2: Withdrawing money


Thread t2 = new Thread(() -> {
try {
account.withdraw(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}, "Thread-2");

// Thread 3: Withdrawing money


Thread t3 = new Thread(() -> {
try {
account.withdraw(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}, "Thread-3");

// Start all threads


t1.start();
t2.start();
t3.start();

}
}

How It Works:

1. Shared Resource: The BankAccount object is shared by all threads.


2. Synchronized Methods:
o deposit(int amount) ensures only one thread can modify the balance while adding money.
o withdraw(int amount) ensures only one thread can modify the balance while subtracting money.
3. Thread Safety: The synchronized keyword prevents race conditions when multiple threads access the deposit and withdraw
methods concurrently.

Key Points:

1. Why Synchronized Method?


o Without synchronization, multiple threads could modify the balance simultaneously, leading to inconsistent results (e.g., a
race condition).
o The synchronized keyword ensures that only one thread can access the critical section at a time.
2. Takeaway:
o Synchronization is crucial when multiple threads share and modify the same resource.
o Using synchronized methods is a simple way to ensure thread safety.
3. Drawback of Synchronized Method:
o It locks the entire method, which may cause performance issues if the method contains non-critical code. In such cases, a
synchronized block would be a better choice.

______________________________________________________________________________________________________________

2. Synchronized Block

• A synchronized block allows you to synchronize only a specific part of a method instead of the entire method. You can
specify the object to lock, providing more flexibility and finer control.
How it works:

• The synchronized block allows you to lock only a critical section within a method, not the entire method.
• You specify an object (lock) to synchronize on (often this or another shared object), and only code within that block is
synchronized.
• This approach enables other threads to execute parts of the method outside the synchronized block, increasing
concurrency.

When to use:

• Use a synchronized block when only a specific part of the method requires thread safety. This can improve performance by
allowing multiple threads to execute non-critical sections concurrently

Example:
package com.example.demo.threads;

class BankAccount {
private int balance = 1000; // Shared resource
private final Object lock = new Object(); // Explicit lock object

// Method to deposit money


public void deposit(int amount) {
System.out.println(Thread.currentThread().getName() + " is trying to deposit: " + amount);
synchronized (lock) { // Synchronized block
balance += amount;
System.out.println(Thread.currentThread().getName() + " completed deposit. New balance: " + balance);
}
}

// Method to withdraw money


public void withdraw(int amount) {
System.out.println(Thread.currentThread().getName() + " is trying to withdraw: " + amount);
synchronized (lock) { // Synchronized block
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " completed withdrawal. New balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " failed to withdraw due to insufficient balance.");
}
}
}

// Method to check balance (not synchronized)


public int getBalance() {
return balance;
}
}

public class SynchronizedBlockExample {


public static void main(String[] args) {
BankAccount account = new BankAccount(); // Shared resource
// Thread 1: Depositing money
Thread t1 = new Thread(() -> account.deposit(500), "Thread-1");

// Thread 2: Withdrawing money


Thread t2 = new Thread(() -> account.withdraw(800), "Thread-2");

// Thread 3: Withdrawing money


Thread t3 = new Thread(() -> account.withdraw(900), "Thread-3");

// Start all threads


t1.start();
t2.start();
t3.start();
}
}

How It Works:

1. Shared Resource: The BankAccount object is shared by all threads.

2. Synchronized Block:

o Instead of locking the entire method, only the critical section of code (modification of balance) is locked.

o The lock is explicitly defined using a private Object (named lock) to avoid accidental interference with other synchronized blocks
or methods.

3. Thread Safety: The synchronized block ensures that only one thread at a time can execute the critical section, preventing race
conditions.

You might also like