Proper way to try-catch a semaphore

后端 未结 2 1524
再見小時候
再見小時候 2021-01-14 09:35

What is the proper way to wrap semaphore actions in a try-catch block? What happens if the acquire action is interrupted after it has acquired some number, but not all, of

2条回答
  •  轮回少年
    2021-01-14 10:08

    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.

提交回复
热议问题