Concurrent Bank Account in Java: Thread-Safe Deposits and Withdrawals
Write a Java program that creates a bank account with concurrent deposits and withdrawals using threads.
Sample Solution:
Java Code:
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:
For more Practice: Solve these Related Problems:
- Write a Java program to simulate a bank account with multiple threads performing deposits and withdrawals using synchronized methods to ensure thread safety.
- Write a Java program to implement a bank account class with concurrent transactions using ReentrantLock for fine-grained control.
- Write a Java program to simulate concurrent bank transactions using wait() and notify() to manage overdraft conditions.
- Write a Java program to implement a bank account with concurrent operations using AtomicInteger to ensure consistency without explicit locking.
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.