Leonardo
Leonardo

Reputation: 3191

Hard time with Concurrency in Java

So, I'm having a hard time trying to resolve a college problem... What I need to do is :

I need to create an app that simulates money transfer between accounts using concurrency. I need to create a method which does this transference in a Bank class like this:

transfer(int from, int to, int value)

Then I need to create a TransferThread class which manages this transferences.

Problem is I'm getting deadlocks all the time... What I've done so far:

TransferThread:

public void run() {
        int para,de,valor;
        try
        {
            while(!interrupted())
            {
                para = new Random().nextInt(banco.getNUMCONTAS());
                de = new Random().nextInt(banco.getNUMCONTAS());
                valor = (int) (10000 * Math.random());
                if(de == para)
                    continue;
                banco.transfer(de, para, valor);
                sleep(1);
            }
        }catch(InterruptedException e)
        {
            System.out.println(e.getMessage());
        }
    }

Banco:

  public synchronized void transfer(int de, int para, int valor) {
        while(contas[de].getSaldo() - valor <= 0)
        {
            try
            {
                wait();
            }catch(InterruptedException e)
            {

            }
        }
        notifyAll();
        contas[de].setSaldo(-valor);
        contas[para].setSaldo(valor);
        System.out.println("Conta num: " + contas[de].getNum() + ". Saldo: " + contas[de].getSaldo());
        System.out.println("Conta num: " + contas[para].getNum() + ". Saldo: " + contas[para].getSaldo());
    }

And main:

Banco b = new Banco();
        TransferThread[] threads = new TransferThread[2];
        for(int i = 0; i < 2; i++){
            threads[i] = new TransferThread(b);
            threads[i].start();
        }

How can I make this work?

Upvotes: 0

Views: 254

Answers (2)

paulsm4
paulsm4

Reputation: 121869

Suggestion -

As you know, a "transfer" involves two things, by two different parties: a "Put" and a "Get".

Consider adding these two methods and synchronizing them (instead of the whole "transfer").

Just a thought...

Upvotes: 1

Mateusz Kowalczyk
Mateusz Kowalczyk

Reputation: 2066

Although banking example is very often used when introducing threading to students, the regular ideas it aims to teach are not the issue in your code.

For some reason you seem to be waiting forever when there isn't enough money in the account, and well, it's not going to magically appear there if both threads wait! They are both simply stuck in infinite loop.

Upvotes: 1

Related Questions