本文介绍了Java有界的非阻塞缓冲区,用于高并发情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要一个数据结构来存储服务器端的临时聊天消息。应该是:

Basically I need a data structure to store the temporary chatting messages on the server side. It should be:


  • bounded:因为我不需要存储太多的邮件,客户端会发送请求,新消息每秒。我认为绑定大小应该是最大。在一秒内挂载并发请求。当缓冲区已满时,旧消息将被删除。

  • bounded: because I don't need store too many messages, the client will send request to get the new messages every second. I think the bound size should be the max. mount of concurrent requests in one second. When the buffer is full, the old messages will be removed.

适合高并发访问:我不想使用数据结构synchronizedXXXX,因为在迭代期间,如果其他线程改变了数据结构,例如添加一个消息,它会抛出一个异常,所以我必须锁定整个数据结构,实际上我不在乎如果客户端请求可以获得最后插入的消息,因为他们会在一秒钟后发送一个新的请求,另一方面写操作应该从不延迟。 java.util.concurrency包下的类似的解决方案,但是...

suitable for high concurrent access: I don't want to use the data structure like Collections.synchronizedXXXX, because during the iteration, if other thread changes the data structure, e.g. adds a message, it will throw an Exception, so I have to lock the whole data structure, actually I don't really care if the client request can get the most last inserted message, because they will send a new request after one second, on the other side the write operation should be never delayed. The classes under the package java.util.concurrency seems the solution, but...

非阻塞:LinkedBlockingQueue,ArrayBlockingQueue他们可以有界,在迭代过程中抛出异常,但它们都是阻塞队列。当队列已满时,我想将新元素添加到尾部,并从头部删除旧元素,而不是阻塞在那里,并等待某人删除该头。

non-blocking: LinkedBlockingQueue, ArrayBlockingQueue they could be bounded and won't throw exception during iteration, but they are all blocking queue. When the queue is full, I want to add the new element to the tails and remove the old element from head instead of blocking there and wait for someone to remove the header.



    所以我的问题是有什么好的实现从第三方库?例如Google Guava?
    或者你有更好的想法在服务器上存储临时聊天消息?

So my question is there any good implementation from 3rd library? For example Google Guava?Or maybe you have better idea about storing the temporary chatting messages on server?

非常感谢!

推荐答案

您可以使用Apache Commons 。它符合您的第一个和最后一个标准。为了支持并发性,你可以把基本缓冲区包装在它的同步版本中,如下所示:

You could utilize the Apache Commons CircularFifoBuffer. It meets your first and last criteria. To support concurrency, you can wrap the base buffer in it's synchronized version like so:

Buffer fifo = BufferUtils.synchronizedBuffer(new CircularFifoBuffer());

祝你好运。

这篇关于Java有界的非阻塞缓冲区,用于高并发情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 21:28