尝试捕获信号量的正确方法 [英] Proper way to try-catch a semaphore

查看:66
本文介绍了尝试捕获信号量的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将信号量动作包装在try-catch块中的正确方法是什么?如果获取动作在获取了一定数量(但不是全部)所请求的许可后被中断,会发生什么情况?您怎么知道又要释放多少?释放是否应该在最终"阶段进行,但是如果动作被中断,您是否不可能释放未获得的许可证?

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 the permits requested? How do you know how many to release again? Should the release go in a "finally" block, but then aren't you possibly releasing permits you didn't get if the action was interrupted?

try {
    lock.acquire(permits);

    //Do some things that require synchronization

    //Make sure to release all of the permits again!
    lock.release(permits);
} catch (InterruptedException e) {
    log.error("Interrupted!");
}

推荐答案

Semaphore.acquire(int)方法是全部或不执行操作,您可以获取所有请求的许可,也可以阻止.您可以对代码进行两次尝试,也可以让(可能的)中断异常阻止气泡堆积.

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.

try {
    lock.acquire(permits);

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

气泡获取"异常:

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.

这篇关于尝试捕获信号量的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆