Concurrent Bank Account in Java: Thread-Safe Deposits and Withdrawals
Java Thread: Exercise-7 with Solution
Write a Java program that creates a bank account with concurrent deposits and withdrawals using threads.
Sample Solution:
Java Code:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private double balance;
private Lock lock;
public BankAccount() {
balance = 0.0;
lock = new ReentrantLock();
}
public void deposit(double amount) {
lock.lock();
try {
balance += amount;
System.out.println("Deposit: " + amount);
System.out.println("Balance after deposit: " + balance);
} finally {
lock.unlock();
}
}
public void withdraw(double amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal: " + amount);
System.out.println("Balance after withdrawal: " + balance);
} else {
System.out.println("Try to Withdraw: " + amount);
System.out.println("Insufficient funds. Withdrawal cancelled.");
}
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
Thread depositThread1 = new Thread(() -> account.deposit(1000));
Thread depositThread2 = new Thread(() -> account.deposit(300));
Thread withdrawalThread1 = new Thread(() -> account.withdraw(150));
Thread withdrawalThread2 = new Thread(() -> account.withdraw(1200));
depositThread1.start();
depositThread2.start();
withdrawalThread1.start();
withdrawalThread2.start();
}
}
Sample Output:
Deposit: 1000.0 Balance after deposit: 1000.0 Withdrawal: 150.0 Balance after withdrawal: 850.0 Deposit: 300.0 Balance after deposit: 1150.0 Try to Withdraw: 1200.0 Insufficient funds. Withdrawal cancelled.
Pictorial Presentation:
Explanation:
In the above exercise, the BankAccount class represents a bank account with a balance. For deposit and withdrawal methods, it uses a "ReentrantLock" to synchronize access, so that different threads can execute them concurrently without conflict.
In the deposit method, the lock is acquired before updating the balance with the deposited amount. The lock is acquired in the withdraw method before checking the balance and completing the withdrawal.
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java thread Programming - Simultaneous Website Crawling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/thread/java-thread-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics