I have a use case like this. One of my method takes a List as parameter. I need to protect the critical section if and only if atleast one of the object is already locked by some other thread. How can achieve using java.util.concurrent package? I can think of simple HashTable based solution, something like
class ContainsCriticalSections {
HashTable<SomeObject, Thread> map; //shared by multiple threads
someCriticalMethod(List<SomeObject> objects) {
acquireLocks(objects);
//do critical task
releaseLocks(objects);
}
synchronized acquireLock(List<SomeObject> objects) {
bool canLock = false;
while (!canLock) {
for (SomeObject obj : objects) {
if (!map.contains(obj)) {
canLock = true;
}
else if(map.get(obj).equals(Thread.currentThread())) {// ensuring re-entrace
canLock = true;
}
else {
canLock = false;
}
}
if (!canLock) {
wait();
}
}
for (SomeObject obj : objects) {
map.put(obj, Thread.currentThread());
}
}
synchronized releaseLock(List<SomeObject> objects) {
for (SomeObject obj : objects) {
map.reomve(obj);
}
notify();
}
}
So in the above case if two invocations with A,B,C and D, E, F don't block. But, A, B, C and A, E, F will block.
but, I strongly feel there will some established paradigm here (using java.util.Concurrent).