简体   繁体   中英

Flow control on blocking queue and SocketChannel write

I have a blocking queue where multiple writers are writing. I want to put a transaction control mechanism where not more than, say, 50 writers(or near) can write per second. Is there a way I can achieve it?

Edit 1: There is a similar requirement to be done with SocketChannel write method. That is to allow n writers to write per second. The value of n varies. I need not worry about that.

Another Edit: I'm thinking of using a Cyclic Barrier which I will release & reset every second. Am I going the right direction?

I do not think thaT 1 semaphore for 50 writers is enough.

What you could do, would be to, for instance have a pool of tickets and a mechanism which issues them. The size of the pool would allow you to stipulate the maximum amount of writers and the mechanism which issues them would allow you to control the flow.

Essentially, the flow would be something like so:

  1. A writer requests a ticket. You can use a semaphore to vlock access for other threads while the wrjter is given a ticket.
  2. Once a writer has a ticket, it writes to the buffer.
  3. The writer returns the ticket (again, you could use a semaphore to control access to this section so that at any one point in time a writer is either requesting or returning s ticket).

Finally I mixed two solution to achieve what I wanted. I used bounded semaphores to limit the writers at any point of time along with timed cyclic barrier which helped me define the total writes/second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM