2

In my implementation I use DelayQueue to prevent too many concurrent access of my method. I found that DelayQueue use internal lock on both methods poll and offer, but in my case I need to do something like this:

if(Objects.nonNull(delayQueue.poll())) {
   delayQueue.offer(...);
}

And those few lines of code are not atomic right? I can add my own ReentrantLock and do something like:

try {
   lock.lock();
   if(poll()) {
      offer(...)
   }
finally {
   lock.unlock();
}

But it looks redundant for me as we have now 2 internal calls to lock/unlock and one external.

Is there a better way to do it?

Orest
  • 6,548
  • 10
  • 54
  • 84
  • 1
    What is your code supposed to do? `DelayQueue` might not be the right choice. – Kayaman Mar 19 '18 at 18:26
  • Besides, that code **is** thread-safe. What it isn't is *atomic*. Do you need it to be atomic? – Kayaman Mar 19 '18 at 18:33
  • I have 10 predefined elements in the queue and after I poll them I want to add them back in 10 seconds. Actually it a kind of limiter to prevent too many concurrent accesses to my method – Orest Mar 19 '18 at 18:36
  • Why do you want to do that? Surely your program has nobler purposes than adding things to a queue forever. – Kayaman Mar 19 '18 at 18:37
  • @Kayaman I've edited my question – Orest Mar 19 '18 at 20:47
  • Okay, so what you want is *throttling*. If you're not opposed to using frameworks, [RateLimiter](https://google.github.io/guava/releases/23.0/api/docs/index.html?com/google/common/util/concurrent/RateLimiter.html) would be exactly what you need. A simple `Semaphore` would work if you don't care about the rate, just the amount of concurrent access. – Kayaman Mar 19 '18 at 20:50
  • Actually yes RateLimiter would be ideal for me, but I found that it works in a way that "requests being smoothly spread over each second" and in case all calls would be done in first 10ms it would block all of them except one. In other words I don't wont to have them smoothly spread I wont to have exact number of calls per second no matter when – Orest Mar 19 '18 at 21:11
  • So wouldn't a simple semaphore work then? Provided that your threads can keep up. – Kayaman Mar 19 '18 at 21:16

0 Answers0