单个java信号量上的死锁?
在我最近的一个答案中,我给出了一个限制对内存资源访问的理论信号量示例:
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);
}
我认为如果分配交错不好,这可能是死锁的根源:
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);
我的观察是真的吗? 如果是,如何避免这种情况(例如定时等待和回滚)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,在这里使用 Semaphore.tryAcquire(permits, timeout, timeUnit) 是明智的做法。 显然,你必须小心地在
finally
块中释放信号量以避免泄漏......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 afinally
block to avoid leaks...