Java bounded non-blocking buffer for high concurrent situation

前端 未结 5 1801
小蘑菇
小蘑菇 2021-02-06 05:25

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

  • bounded: because I don\'t need store too many messa

相关标签:
5条回答
  • 2021-02-06 05:58

    You can use LinkedBlockingQueue with the non-blocking methods offer (or add) and poll to access it. You can create it with a fixed capacity to make it bounded.

    LinkedBlockingQueue<String> myStrings = new LinkedBlockingQueue<String>(100);
    myStrings.offer("Hi!"); // returns false if limit is reached
    myStrings.add("Hi, again!"); // throws exception if limit is reached
    String s = myStrings.poll(); // returns null if queue is empty
    
    0 讨论(0)
  • 2021-02-06 06:04

    LinkedTransferQueue is a blocking, unbounded queue that doesn't enforce strict FIFO ordering. It will only block when taking from an empty queue, but never on adding to one. You could add a soft cap to evict elements by adding either a size or read & write counters.

    Depending on your requirements, you may be able to write a custom lock-free ring buffer.

    0 讨论(0)
  • 2021-02-06 06:10

    Did you take a look at ConcurrentLinkedQueue? The page says

    This implementation employs an efficient "wait-free" algorithm...

    Wait-freedom is one of the strongest guarantee you can obtain....

    0 讨论(0)
  • 2021-02-06 06:13

    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());
    

    Good luck on the project.

    0 讨论(0)
  • 2021-02-06 06:14

    You can add non-blocking behaviour to an ArrayBlockingQueue by surrounding it with a conditional offer() statement, where failure of the queue to accept the offer results in the head being dropped and the offer being re-made:

        public class LearnToQueue {
    
    
        public static void main(String[] args){
            Queue<Integer> FIFO = new ArrayBlockingQueue<Integer>(4);
    
            int i = 0;
    
            while ( i < 10 ){
    
                if (!FIFO.offer(i)){
                // You can pipe the head of the queue anywhere you want to
                    FIFO.remove();
                    FIFO.offer(i);
                }
                System.out.println(FIFO.toString());
                i++;
    
            }
        }
    
        }
    
    0 讨论(0)
提交回复
热议问题