1

How to wait on multiple Blocking Queues in Java?

For example, if have a customer who wants to enter into a waiting Lounge. There are 3 waiting Lounges and each lounge has a fixed number of seats.

Considering this a concurrent programming question, how can a customer wait on all of this simultaneously.

  terminal.waitingArea1.enterWaitingArea(this);
  terminal.waitingArea2.enterWaitingArea(this);
  terminal.waitingArea3.enterWaitingArea(this);

If I get into a single area, I should give up waiting on other's. How can this be done?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Chandan S R
  • 61
  • 1
  • 8
  • a little bit unclear... what do you mean by *wait on all of this simultaneously*? – Eugene Aug 15 '18 at 09:43
  • Why could he sit in 3 different lounges at once? – Lino Aug 15 '18 at 09:48
  • @Lino: The customer probably can not sit in all three lounges at once, but they can sit in *any* of them. They thus wants to wait until a seat is free in any of them, and then stop wait for the others. – Lii Aug 15 '18 at 10:44
  • 1
    Possible duplicate of [Java - wait on multiple BlockingQueue's in parallel](https://stackoverflow.com/questions/36330623/java-wait-on-multiple-blockingqueues-in-parallel) – Lii Aug 15 '18 at 10:48
  • I would wrap all access to 'lounges' in a manager object - call it hostess - and do the locking there. Use a Sempahore with a number of permits equal to the total number of seats. When a guest leaves, hostess releases a permit and notes which lounge has a seat available so the next guest is directed there. Something along those lines.. – user1373164 Aug 15 '18 at 10:50
  • @Chandan S R: This is an interesting question! But it seems like it has been asked before. We should try to come up with a better answer for that question instead, I don't like any of the given ones. – Lii Aug 15 '18 at 10:55
  • @Lii , yes this is an interesting problem which we come across during concurrent programming. Please let me know, if you come across some solution. – Chandan S R Aug 16 '18 at 16:33

2 Answers2

0

The basic logic would be:

  1. Use a boolean variable (i.e., a flag), initially set to false.

  2. When the object gets into a waiting area, check the flag.

  3. If the flag is false, set it to true, then carry out the required operations.

  4. If the flag is true, simply remove the object from the queue, without doing anything.

In case you are using multiple threads, use synchronized on the object.

Susmit Agrawal
  • 3,649
  • 2
  • 13
  • 29
0

Keep the references to queues in Customer that this Customer is waiting for. When

get into a single area

Remove this Customer from all the queues that this is waiting except this queue, The remove action should be synchronized.

Dongfang Qu
  • 341
  • 1
  • 11