In one of my recent answers, I gave a theoretical semaphore example of limiting access to memory resources:
public static byte[] createArray(int size) throws InterruptedException {
semaphore.acquire(size);
return new byte[size];
}
public static void releaseArray(byte[] array) {
semaphore.release(array.length);
}
I think this can be a source of deadlock if the allocation interleaving is bad:
semaphore = new Sempaphore(30, true);
// T1 T2
//-------------------------- ----------------------
a1 = createArray(10); // 20
a3 = createArray(10); // 10
a2 = createArray(15); // wait
a4 = createArray(15); // wait
// ... // ...
releaseArray(a1); releaseArray(a3);
releaseArray(a2); releaseArray(a4);
Is my observation true? If yes, how can I avoid this situation (e.g timed wait and rollback)?