P
P
per4uk22014-12-27 03:48:08
Java
per4uk2, 2014-12-27 03:48:08

Is it possible to lock two objects in a synchronized block?

public void transfer(int from, int to, double amount) {
        synchronized (accounts) {//double[] accounts - массив счетов в банке
                if (accounts[from] < amount) return;
                accounts[from] -= amount;
                accounts[to] += amount;
        }
}

This feature transfers money from one account to another. In this case, the entire array of accounts is blocked, is it possible to somehow block only two accounts (only accounts[from] and accounts[to]). For example, so that the execution of transfer(1, 2, .. ) does not block transfer(3, 4, .. )?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bimeg, 2014-12-27
@per4uk2

synchornize(accounts[Math.min(from, to)])
{
    synchorize(accounts[Math.max(from, to)])
    {
    }
}

Y
yuraminsk, 2015-01-01
@yuraminsk

You can

Can
you are not blocking objects, but threads that can access these objects, i.e. blocking on the object!
Specifically, in your case, the only valid implementation will be
synchronized (accounts) {} - both for writing and reading, i.e. any operations on the contents of the array. otherwise not "happens before" and not thread safe. what you want to do is called "finer-grained concurrency".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question