Reputation: 1
The method tryAcquire(long timeout, TimeUnit unit)
in Semaphore does not return immediately. The threads are not blocked and all threads are allowed to acquire the semaphore even though one of the threads is acquiring the semaphore.
I am trying to implement flow control for publishing messages when a broker is notifying the subscribers about the state information change from the previous publish message on the same topic.
I have made a first thread acquiring the semaphore to sleep for 10 seconds before releasing the semaphore and in the meantime, I made another thread to acquire the semaphore while the first thread is still sleeping for 10 seconds and the second thread can still acquire the semaphore. I would like the program to return immediately if the semaphore is not available. Don't know what's the issue. Any suggestions would be really helpful.
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();
}
Upvotes: 0
Views: 2769
Reputation: 159155
tryAcquire(long timeout, TimeUnit unit)
method in Semaphore does not return immediately.
It's not supposed to. If you read the documentation, i.e. the javadoc, you find:
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.
If you want it to return immediately, call tryAcquire()
(without parameters):
If no permit is available then this method will return immediately with the value
false
.
Upvotes: 5