Page 1 of 1

Deadlock in Multi-Threaded Application

Posted: Wed Nov 06, 2024 9:03 pm
by nostalgia
Hi,
I'm new here
Pls help me with this issue

Code: Select all

```java
public class Account {
    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public void withdraw(int amount) {
        balance -= amount;
    }

    public void deposit(int amount) {
        balance += amount;
    }

    public static void transfer(Account from, Account to, int amount) {
        synchronized (from) {
            System.out.println(Thread.currentThread().getName() + " locked " + from);
            
            // Simulate processing
            try { Thread.sleep(100); } catch (InterruptedException e) { }

            synchronized (to) {
                System.out.println(Thread.currentThread().getName() + " locked " + to);
                from.withdraw(amount);
                to.deposit(amount);
                System.out.println(Thread.currentThread().getName() + " transferred " + amount);
            }
        }
    }
}

public class DeadlockDemo {
    public static void main(String[] args) {
        final Account accountA = new Account(1000);
        final Account accountB = new Account(2000);

        // Thread T1 - transfer from AccountA to AccountB
        Thread t1 = new Thread(() -> Account.transfer(accountA, accountB, 100), "Thread-1");

        // Thread T2 - transfer from AccountB to AccountA
        Thread t2 = new Thread(() -> Account.transfer(accountB, accountA, 200), "Thread-2");

        t1.start();
        t2.start();
    }
}
```
Is this a deadlock or am i wrong?

Re: Deadlock in Multi-Threaded Application

Posted: Wed Nov 06, 2024 11:22 pm
by admin
It could result in a deadlock. What are your thoughts ?