Sheb
Sheb

Reputation: 23

Queue which wait until something happen

I want to implement the queue, which waits for shared resource. When this resource is free, queue take the first added element and change the info in this resource. But when no, just wait. Is there any queues in concurrency library that can do this? Or i need to write my own queue? Or is there are a better way to do this? Thanks for help)

Upvotes: 1

Views: 549

Answers (1)

Trevor Freeman
Trevor Freeman

Reputation: 7232

It sounds like you want two things.

  1. A BlockingQueue instance (such as ArrayBlockingQueue) for your queue of tasks to perform on the resource.

  2. A lock for the resource for your threads to wait on until the resource is available.

Your threads can then either take an item off the queue and wait on the resource lock, or wait on the resource lock and then try to take an item off the queue while holding that lock.

Waiting and taking from the queue first is the easier design, but your wording in the question makes it seem like you wish to do the opposite and wait on the resource lock first and then try to take from the queue. That workflow is a little bit more complicated in that you should poll() from the queue (instead of take()'ing) and release your resource lock if you do not want to hold it if the queue is empty.

E.g.

  1. Wait on resource lock
  2. ... acquire resource lock
  3. poll from queue
  4. If queue was empty, release resource lock.
  5. If queue was not empty, process queue item.
  6. Release resource lock.
  7. If queue was empty, sleep for a bit..?
  8. Repeat.

Upvotes: 1

Related Questions