In Java, suppose you have an array:
Object[] objs = {o1, o2, ... , oN};
And a critical section:
{
critical();
}
And you wish to execute the critical section while holding the intrinsic lock of every element in objs.
I can think of one way to do this, and it involves an abominable abuse of recursion:
void syncArray(int i) {
if (i >= 0) {
synchronized(objs[i]) {
syncArray(i - 1);
}
} else {
critical();
}
}
syncArray(objs.length - 1);
Besides being ugly, this entails O(N) stack frames, which is probably not great. Is there a better way? What I really want is a way to acquire and release intrinsic locks without the synchronized keyword. Bonus points if you have a non-blocking way to attempt to acquire an intrinsic lock.
Note: I'm not asking if this is a good idea (it's not), just if it's possible. The real-world answer is obviously just to use explicit locks and also do some soul-searching about the wisdom of trying to acquire locks for N objects at once.