Deadlock on a single java semaphore?
-
05-07-2019 - |
Question
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)?
Solution
Yes, using Semaphore.tryAcquire(permits, timeout, timeUnit)
would be the sensible thing to do here. Obviously you've got to be careful to release the semaphore in a finally
block to avoid leaks...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow