[英]How to create Java concurrent queue from which we can blocking-take more than 1 element in single call?
Background: I need to send many small-size messages to WebSocket clients in asynchronous way. 背景:我需要以异步方式向WebSocket客户端发送许多小型消息。 Messages are usually sent in peak, so after some pause I need to send ~5000 messages fast.
消息通常以高峰发送,因此经过一些暂停后,我需要快速发送约5000条消息。 So the problem is:
所以问题是:
The best way would be to group ~20 asyncs per thread, so I need very specific queue : 最好的方法是将每个线程约20个异步组,因此我需要非常具体的队列 :
take()
(so I can start 1...20 async I/O and wait for completness in single thread) take()
(因此我可以启动1 ... 20异步I / O并等待单线程完成) So basically: I need structure like queue that has blocking take(1 to X) waiting elements in single blocking call . 所以基本上: 我需要像队列这样的结构,它在单个阻塞调用中具有阻塞take(1至X)等待元素 。 Pseudocode:
伪代码:
[each of ~50 processing threads]:
messages = queue.blockingTake( max 10 or at least 1 if less than 10 available );
for each message: message.startAsync()
for each message: message.waitToComplete()
repeat
I wouldn't implement a Queue from scratch if it's not really necessary. 如果没有必要,我不会从头开始实施Queue。 A few ideas if you're interested:
有兴趣的一些建议:
Queue> if you have only 1 thread doing the offers. 队列>,如果您只有1个线程在执行商品。 If you have more, the collection has to be sync'd.
如果您还有更多内容,则必须同步该集合。 Like, one offerer peek()-s into the queue, sees that the last collection has too many elements so it creates a new one and offers it.
就像一个报价者peek()-s进入队列一样,它看到最后一个集合包含太多元素,因此它创建了一个新集合并提供了它。
or 要么
A number of running threads where the runnables take elements one by one from the queue. 许多运行线程,其中可运行对象从队列中一个接一个地获取元素。
or 要么
1 queue per sending thread, if you keep the queue references you can then add elements to each of them in a round robin fashion. 每个发送线程1个队列,如果保留队列引用,则可以循环方式向每个元素添加元素。
or 要么
subclass a BlockingQueue of your choice and create a "Collection take(int i)" method with a rewritten version of the normal take(). 将您选择的BlockingQueue子类化,并使用重写版的take()创建“ Collection take(int i)”方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.