1005
Example Language: Java (Bad)
public class BankAccount {
// variable for bank account balance
private double accountBalance;
// constructor for BankAccount
public BankAccount() {
accountBalance = 0;
}
// method to deposit amount into BankAccount
public void deposit(double depositAmount) {
double newBalance = accountBalance + depositAmount;
accountBalance = newBalance;
}
// method to withdraw amount from BankAccount
public void withdraw(double withdrawAmount) {
double newBalance = accountBalance - withdrawAmount;
accountBalance = newBalance;
}
// other methods for accessing the BankAccount object
...
}
However, the deposit and withdraw methods have shared access to the account balance private
class variable. This can result in a race condition if multiple threads attempt to call the deposit and
withdraw methods simultaneously where the account balance is modified by one thread before
another thread has completed modifying the account balance. For example, if a thread attempts
to withdraw funds using the withdraw method before another thread that is depositing funds using
the deposit method completes the deposit then there may not be sufficient funds for the withdraw
transaction.
To prevent multiple threads from having simultaneous access to the account balance variable the
deposit and withdraw methods should be synchronized using the synchronized modifier.
Example Language: Java (Good)
public class BankAccount {
...
// synchronized method to deposit amount into BankAccount
public synchronized void deposit(double depositAmount) {
...
}
// synchronized method to withdraw amount from BankAccount
public synchronized void withdraw(double withdrawAmount) {
...
}
...
}
An alternative solution is to use a lock object to ensure exclusive access to the bank account
balance variable. As shown below, the deposit and withdraw methods use the lock object to set a
lock to block access to the BankAccount object from other threads until the method has completed
updating the bank account balance variable.
Example Language: Java (Good)
public class BankAccount {
...
// lock object for thread access to methods
private ReentrantLock balanceChangeLock;
// condition object to temporarily release lock to other threads
private Condition sufficientFundsCondition;
// method to deposit amount into BankAccount
public void deposit(double amount) {
// set lock to block access to BankAccount from other threads
CWE Version 4.14
CWE-413: Improper Resource Locking
CWE-413: Improper Resource Locking