Java bounded non-blocking buffer for high concurrent situation

前端 未结 5 1802
小蘑菇
小蘑菇 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 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 FIFO = new ArrayBlockingQueue(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++;
    
            }
        }
    
        }
    

提交回复
热议问题