What is synchronization in java with an example javatpoint

Laura 137 Published: 12/15/2024

What is synchronization in java with an example javatpoint

I'll respond in English as requested.

Synchronization in Java refers to the mechanism that ensures only one thread can execute a particular section of code at a time, preventing multiple threads from accessing the same resource simultaneously. This is achieved through the use of synchronization primitives, such as synchronized blocks, Object.wait(), and notify() methods, which are built into the Java programming language.

Here's an example using synchronized blocks:

Let's say we have a bank account with multiple threads accessing it simultaneously to withdraw funds. Without synchronization, multiple threads could access the account at the same time, potentially leading to incorrect results or even system crashes.

class BankAccount {

private int balance = 1000;

public synchronized void withdraw(int amount) {

if (balance >= amount) {

balance -= amount;

System.out.println("Withdrew " + amount + ". Balance: " + balance);

} else {

System.out.println("Insufficient funds.");

}

}

}

In this example, we have a BankAccount class with a withdraw() method that allows multiple threads to withdraw money from the account. However, without synchronization, multiple threads could access the balance field simultaneously and potentially overwrite each other's changes.

To prevent this, we use the synchronized keyword to ensure that only one thread can execute the withdraw() method at a time. When one thread calls withdraw(), it acquires the lock on the BankAccount object, preventing other threads from entering the same method until the current thread finishes executing.

Here's an example of how multiple threads might interact with this class:

public class Main {

public static void main(String[] args) {

BankAccount account = new BankAccount();

Thread t1 = new WithdrawThread(account, 200);

Thread t2 = new WithdrawThread(account, 300);

t1.start();

t2.start();

try {

t1.join();

t2.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

class WithdrawThread extends Thread {

private BankAccount account;

private int amount;

public WithdrawThread(BankAccount account, int amount) {

this.account = account;

this.amount = amount;

}

public void run() {

account.withdraw(amount);

}

}

In this example, we have two threads, t1 and t2, that both try to withdraw money from the same bank account. Without synchronization, these operations could interfere with each other, leading to incorrect results.

By using the synchronized keyword, we ensure that only one thread can execute the withdraw() method at a time, preventing interference between threads and ensuring correct operation of our bank account class.

Synchronization in Java is essential for creating thread-safe programs that can handle concurrent access from multiple threads. By using synchronization primitives effectively, you can avoid common problems like data corruption, race conditions, and deadlocks.

Why do we use synchronized in Java?

I'd be happy to explain the concept of synchronized methods and blocks in Java!

In Java, synchronization is a mechanism used to achieve thread safety when multiple threads share common resources. Synchronization ensures that only one thread can access a shared resource at any given time.

Imagine you're trying to withdraw cash from your bank account simultaneously with your friend. You both reach the ATM machine at the same time and start withdrawing money. However, due to some technical glitch, there's a small delay between when you initiate the withdrawal and when the actual transaction takes place. If your friend happens to withdraw more money than what was initially available in your account, this would cause an error or even a financial loss for both of you.

This scenario is similar to what can happen in Java if multiple threads try to access a shared resource like a variable, method, or object simultaneously. To avoid such issues and maintain data consistency, we use synchronization in Java.

Synchronized methods:

A synchronized method ensures that only one thread can execute the method at any given time. When you declare a method as synchronized, it means that the JVM will acquire the lock on the object before allowing the method to be executed. This ensures that once a thread starts executing the method, no other thread can access the same method until the first thread finishes or is interrupted.

For example:

public class BankAccount {

private int balance = 1000;

public synchronized void withdraw(int amount) {

if (balance >= amount) {

balance -= amount;

} else {

System.out.println("Insufficient funds!");

}

}

}

In the above example, the withdraw method is declared as synchronized. This means that whenever multiple threads try to withdraw money simultaneously, only one thread will be allowed to execute the withdraw method at any given time. The other threads will have to wait until the first thread finishes its operation or is interrupted.

Synchronized blocks:

A synchronized block, on the other hand, is used when you want to ensure that a specific section of code within a method is executed in a thread-safe manner.

For example:

public class BankAccount {

private int balance = 1000;

public void transfer(BankAccount recipient, int amount) {

synchronized (this) { // Synchronizing on the current object

if (balance >= amount) {

balance -= amount;

recipient.balance += amount; // This line should also be synchronized!

} else {

System.out.println("Insufficient funds!");

}

}

}

}

In this example, we use a synchronized block to ensure that when multiple threads try to transfer money simultaneously, the transfer method will execute in a thread-safe manner. The line where we update the recipient's balance should also be synchronized for thread safety!

To summarize, synchronization in Java is crucial for maintaining data consistency and avoiding issues like concurrent modification of shared resources. By using synchronized methods or blocks, you can ensure that only one thread can access shared resources at any given time.

Hope this explanation helps!