使用 FIFO 缓冲区的正确方法



我有这个FIFO,我将用它来存储来自网络服务器的数据:

 Buffer nServerFifo = (Buffer) BufferUtils.synchronizedBuffer(new CircularFifoBuffer(200));
    // Insert into to the Network Server Buffer    
    public void nServerFifoAdd(String string){
        nServerFifo.add(string);        
    }
    // Get data from the Network Server Buffer
    public Object nServerFifoGet(){         
        Object string = nServerFifo.get();    
        nServerFifo.remove(string);
        return string;           
    }

我的问题是存储数据插入并从缓冲区获取数据的正确方法是什么?我是否需要在获得 if 或缓冲区完成此操作后删除数据?您知道我可以存储到缓冲区中的最大字符串长度大小是多少吗?

它更好地使用ArrayBlockingQueue class存在于java.util.concurrent包中,它是线程安全的。

BlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
queue.put("Vivek");   // To insert value into Queue
queue.take();         // To take the value out of Queue

假设您使用的是共享资源集合中的类:

  1. 如果使用 remove() 方法,则无需额外删除任何内容
  2. 缓冲区存储对象引用,而不是字符串,因此它受分配的插槽数量的限制。 在您的情况下,在缓冲区已满之前,您最多可以添加 200 个任意长度的字符串,受程序可用的总内存的限制。

正如 Kumar 指出的那样,您可能最好使用 Java 运行时库队列类,因为它们为您处理同步,而 Commons Collections 类要求您自己锁定迭代器。

最新更新