gpt4 book ai didi

java - 信号量 tryAcquire() 方法不会立即返回

转载 作者:行者123 更新时间:2023-12-01 19:34:27 24 4
gpt4 key购买 nike

Semaphore 中的方法 tryAcquire(long timeout, TimeUnit unit) 不会立即返回。线程不会被阻塞,并且即使其中一个线程正在获取信号量,也允许所有线程获取信号量。当代理通知订阅者有关同一主题的上一条发布消息的状态信息更改时,我试图实现发布消息的流量控制。

我已经让第一个获取信号量的线程在释放信号量之前 hibernate 10 秒,同时,我让另一个线程获取信号量,而第一个线程仍然 hibernate 10 秒,第二个线程仍然可以获取信号量。如果信号量不可用,我希望程序立即返回。不知道是什么问题。任何建议都会非常有帮助。

try {

if(semaphore.tryAcquire(this.request_handling_time,
TimeUnit.MILLISECONDS)) {
updateResource(resource, request);
response = channel.createResponse(request, CoapResponseCode.Changed_204);
logger.info("content changed");
try {

if(request.getMaxAgeTopic()>=0) {

((PubSubTopic) resource).setmaxAgeTopicValue(request.getMaxAgeTopic());
}
}catch(NullPointerException ex){

if(((PubSubTopic) resource).getmaxAgeTopicValue() > 0){
((PubSubTopic) resource).updateTopicLifeTime();
}
}
resource.changed(); // send notifications to the subscribers

// send notifications to the pendingRequest Clients if present
if(((PubSubTopic) resource).getPendingSubscribe().size() > 0) {
((PubSubTopic) resource).notifyPendingRequest();
}
try {
Thread.sleep(10000);


}
catch (@SuppressWarnings("unused") InterruptedException e){
/*do nothing*/
}

semaphore.release();
}else {
logger.info("Too many requests on topic "+resource.getPath());
response = channel.createResponse(request,
CoapResponseCode.Too_Many_Requests_429);

response.setMaxAge(retry_time_after_too_many_requests);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
semaphore.release();
}

最佳答案

tryAcquire(long timeout, TimeUnit unit) method in Semaphore does not return immediately.

这是不应该的。如果您阅读文档,即javadoc ,你会发现:

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:

  • Some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit; or
  • Some other thread interrupts the current thread; or
  • The specified waiting time elapses.

如果您希望它立即返回,请调用 tryAcquire() (不带参数):

If no permit is available then this method will return immediately with the value false.

关于java - 信号量 tryAcquire() 方法不会立即返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com