Multithreaded Mini Banking System with Generics, Reflection, and Synchronization

Multithreaded Mini Banking System with Generics, Reflection, and Synchronization

A complex Java program that simulates a mini banking system. It uses various advanced Java concepts like generics, multithreading, synchronization, and reflection. After the code, I'll explain its components.

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// Account class with thread-safe operations
class Account {
    private String accountNumber;
    private double balance;
    private final Lock lock = new ReentrantLock();

    public Account(String accountNumber, double balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    public void deposit(double amount) {
        lock.lock();
        try {
            balance += amount;
        } finally {
            lock.unlock();
        }
    }

    public void withdraw(double amount) throws Exception {
        lock.lock();
        try {
            if (balance < amount) {
                throw new Exception("Insufficient funds");
            }
            balance -= amount;
        } finally {
            lock.unlock();
        }
    }

    public double getBalance() {
        lock.lock();
        try {
            return balance;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public String toString() {
        return "Account{" + "accountNumber='" + accountNumber + '\'' + ", balance=" + balance + '}';
    }
}

// Bank class managing multiple accounts
class Bank {
    private List<Account> accounts = new ArrayList<>();

    public void addAccount(Account account) {
        accounts.add(account);
    }

    public <T> void executeTransaction(T account, Transaction<T> transaction) {
        transaction.perform(account);
    }

    public void showAllAccounts() {
        accounts.forEach(System.out::println);
    }
}

// Functional interface for transactions
@FunctionalInterface
interface Transaction<T> {
    void perform(T account);
}

// Main class demonstrating the mini banking system
public class MiniBankingSystem {
    public static void main(String[] args) {
        Bank bank = new Bank();

        // Adding accounts
        Account account1 = new Account("12345", 1000.00);
        Account account2 = new Account("67890", 2000.00);

        bank.addAccount(account1);
        bank.addAccount(account2);

        // Using reflection to invoke methods dynamically
        try {
            Method depositMethod = Account.class.getMethod("deposit", double.class);
            depositMethod.invoke(account1, 500.00);
            depositMethod.invoke(account2, 1000.00);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Running transactions in parallel
        Thread t1 = new Thread(() -> {
            try {
                account1.withdraw(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                account2.withdraw(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Using generics with lambda expressions for transactions
        bank.executeTransaction(account1, (acc) -> acc.deposit(700));
        bank.executeTransaction(account2, (acc) -> acc.deposit(400));

        // Displaying all account details
        bank.showAllAccounts();
    }
}
        

Explanation:

1. Account Class:

- Fields: accountNumber, balance, and a ReentrantLock for thread safety.

- Methods:

- deposit(double amount): Adds the amount to the balance.

- withdraw(double amount): Deducts the amount from the balance if sufficient funds are available.

- getBalance(): Returns the current balance.

- toString(): Returns a string representation of the account.

2. Bank Class:

- Fields: accounts, a list to store multiple accounts.

- Methods:

- addAccount(Account account): Adds an account to the list.

- <T> void executeTransaction(T account, Transaction<T> transaction): Executes a transaction using a generic type and a functional interface.

- showAllAccounts(): Displays all accounts.

3. Transaction Interface:

- A functional interface with a single method perform(T account) to define a transaction.

4. MiniBankingSystem Class (Main):

- Creates a Bank instance.

- Adds two Account instances to the bank.

- Uses Java reflection to dynamically invoke the deposit method on accounts.

- Creates and starts two threads to perform withdrawals concurrently, demonstrating thread safety.

- Uses generics and lambda expressions to perform deposits through the executeTransaction method.

- Displays all account details at the end.

This code is complex due to the use of advanced Java features such as thread synchronization with locks, reflection for dynamic method invocation, generics, lambda expressions, and functional interfaces. These concepts work together to simulate a mini banking system that handles concurrent transactions safely and efficiently.

要查看或添加评论,请登录

Towfik Alrazihi的更多文章

社区洞察

其他会员也浏览了