+ 1
code to avoid deadlock in java where N threads are accessing N shared resources ?
3 Antworten
+ 1
May you should share the resources through a dispatcher object which handles the access? Depends on the situation, but using locks for those operations involved in potential deadlock seems a valid solution, however, it needs high awareness and planning not to make a human mistake.
Another solution (or a version of the above?) is to gain the lock of all resources needed for a process before its start under one shared lock (maybe the dispatcher object itself):
if (dispatcher.lock(<resource locks>)) {
... use resources
dispatcher.release(<resources locks>);
} else {
not all resources were available at the time
placed into a loop and retry...?
}
And the dispatcher manager class is like that:
boolean lock(lockids...) {
synchronized(this) {
lock them if possible & return true
return false elseway (and lock none of them)
}
}
I did not met with deadlock programming yet (only multithreading synchronization), but these are my tips/ideas, how I would approach the problem :)
+ 1
I wrote a key-set based synchronization lock, which can be used for such purpose. The keys can be loaded objects of data, an id of resource or the file path, for example. The important thing is to use the same key for the same resource in every lock made.
Example usage:
//nr stands for "needed resource"
SyncLock lock = new SyncLock(nr1, nr2);
if (lock.take()) {
//use resources
lock.release();
}
Notice, that this only provides safety in your problem if you lock all resources with one lock on the beginning. Or, if you abort your process when an inner lock cannot be taken (in time). Like that:
if (lock1.takeIn(150)) {
//use resources of lock1
if (lock2.takeIn(100)) {
//use resources of both lock
lock2.release();
} else {
//request for 2nd resources timed out
}
lock1.release();
} else {
//request for 1st resources timed out
}
This way all deadlocked processes will exit when timed out and free the deadlock automatically.
https://code.sololearn.com/cyJm3QmA2hU2
0
The SyncLock is fully written and working.
If you have further questions about the lock itself or its usage, feel free to comment on my linked code :)