Proper way to try-catch a semaphore

筅森魡賤 提交于 2019-12-01 21:29:56

The Semaphore.acquire(int) method is an all or nothing operation, either you get all the permits requested or you block. You can use a double try around your code, or let the (possible) interrupted exception from acquiring bubble up your call stack.

Double try block:

try {
    lock.acquire(permits);

    try {
        // do some stuff here
    } finally {
        lock.release(permits);
    }
} catch(final InterruptedException ie) {
    // handle acquire failure here
}

Bubble 'acquisition' exception:

lock.acquire(permits);

try {
    // do some stuff here
} finally {
    lock.release(permits);
}

On a tangent, do keep in mind that semaphores must be kept balanced by strict programming convention, so you should always release as many permits as you acquired.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!