Java synchronized example

Edison 109 Published: 07/19/2024

Java synchronized example

Here's an example of a Java synchronized method:

public class Bank {

private int balance = 0;

public void deposit(int amount) {

try {

Thread.sleep(100);

} catch (InterruptedException e) {

// Handle exception

}

int newBalance = balance + amount;

balance = newBalance;

System.out.println("Deposited " + amount + ". New balance is " + balance);

}

public void withdraw(int amount) {

try {

Thread.sleep(100);

} catch (InterruptedException e) {

// Handle exception

}

if (balance >= amount) {

int newBalance = balance - amount;

balance = newBalance;

System.out.println("Withdrawn " + amount + ". New balance is " + balance);

} else {

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

}

}

public synchronized void transfer(Bank bank, int amount) {

try {

Thread.sleep(100);

} catch (InterruptedException e) {

// Handle exception

}

bank.withdraw(amount);

System.out.println("Transferred " + amount + ". New balance is " + getBalance());

}

public int getBalance() {

return balance;

}

}

This Bank class simulates a simple banking system with methods for depositing, withdrawing, and transferring funds. The transfer method is synchronized to ensure that it cannot be executed simultaneously by multiple threads.

Here's an example of how you might use this class in a multi-threaded context:

public class Main {

public static void main(String[] args) {

Bank myBank = new Bank();

Bank yourBank = new Bank();

Thread myThread = new Thread(() -> {

for (int i = 0; i < 5; i++) {

myBank.transfer(yourBank, 100);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// Handle exception

}

}

});

Thread yourThread = new Thread(() -> {

for (int i = 0; i < 5; i++) {

yourBank.transfer(myBank, 100);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// Handle exception

}

}

});

myThread.start();

yourThread.start();

try {

myThread.join();

yourThread.join();

} catch (InterruptedException e) {

// Handle exception

}

System.out.println("Final balances:");

System.out.println("My bank: " + myBank.getBalance());

System.out.println("Your bank: " + yourBank.getBalance());

}

}

In this example, we create two threads that simulate transactions between two banks. The transfer method in the Bank class is synchronized to ensure that it cannot be executed simultaneously by multiple threads.

By using the synchronized keyword on the transfer method, we guarantee that only one thread can execute this method at a time. This ensures that the banking system remains consistent and accurate even in the presence of concurrent transactions.

For example, if two threads were to transfer funds from one bank to another simultaneously, without synchronization, it's possible that one transaction would succeed while the other fails due to insufficient funds. By using synchronization, we can ensure that these transactions are executed in a way that maintains the integrity of the banking system.

java synchronized class

I'll respond in English!

A synchronized class in Java is a class that uses synchronization techniques to control access to its instances and methods. In Java, synchronization is used to ensure that only one thread can execute a particular section of code at any given time. This is useful when you want to ensure that certain actions are performed atomically, without being interrupted by other threads.

Here's an example of how you might define a synchronized class in Java:

public class SynchronizedClass {

private Object lock = new Object();

public void doSomething() {

// Critical section of code

synchronized (lock) {

try {

System.out.println("Starting...");

Thread.sleep(1000);

System.out.println("Finishing!");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

In this example, the doSomething method is synchronized on an instance of the Object class. This means that only one thread can execute this method at a time.

Here's what happens when multiple threads try to call the doSomething method concurrently:

The first thread to call doSomething acquires the lock (i.e., the lock object) and executes the critical section of code. If another thread tries to call doSomething while the first thread is still executing, it will block until the first thread releases the lock. Once the first thread has finished executing the critical section, it releases the lock, allowing other threads to acquire it and execute the method.

By using synchronization, you can ensure that certain actions are performed atomically and consistently, even in the presence of multiple concurrent threads.

Here are some benefits of using synchronized classes:

Atomicity: Synchronization ensures that certain actions are performed as a single unit, without being interrupted by other threads. Consistency: Synchronized methods ensure that the internal state of an object remains consistent, even when multiple threads are accessing it concurrently. Mutual Exclusion: Synchronization ensures that only one thread can execute a particular method at any given time, preventing conflicts and errors.

Some common scenarios where you might use synchronized classes include:

Database transactions: When performing database operations, synchronization ensures that either all or none of the changes are committed. File access: When multiple threads need to access a file concurrently, synchronization ensures that only one thread can modify the file at any given time. Thread-safe data structures: When implementing data structures like queues or stacks, synchronization ensures that they remain consistent and reliable in the presence of concurrent access.

In summary, synchronized classes are a powerful tool for controlling access to instances and methods in Java, ensuring atomicity, consistency, and mutual exclusion in the face of concurrency.