Java
February 9
Concurrent Bank Transaction System in Java
Below is an example of a concurrent bank transaction system in Java. In this example, we model a bank account with methods for deposit, withdrawal, and a transfer operation that involves two accounts. We use a ReentrantLock
in each account to ensure that modifications to the account balance are thread-safe, and we take care to avoid deadlocks when transferring funds between two accounts.
- Fields & Lock:
Each account has a uniqueid
, abalance
, and a dedicatedReentrantLock
to protect its state. - Deposit & Withdraw:
The methodsdeposit()
andwithdraw()
lock the account before modifying the balance to ensure thread safety. - Transfer Method:
The statictransfer()
method transfers funds between two accounts.
This example demonstrates key concurrency concepts in a real-world banking scenario, including proper synchronization with locks, avoiding deadlock by enforcing a lock order, and managing concurrent tasks using an ExecutorService
.