使用FIFO缓冲区的正确方法

时间:2012-06-17 17:44:47

标签: java apache-commons apache-commons-collection

我有这个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之后是否需要删除数据?或者这是由缓冲区完成的?你知道我可以存储到缓冲区的最大字符串长度是多少吗?

2 个答案:

答案 0 :(得分:3)

它更好地使用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 :(得分:1)

假设您正在使用Commons Collections中的类:

  1. 如果您使用remove()方法,则无需另外删除任何内容
  2. 缓冲区存储对象引用,而不是字符串,因此它受分配的插槽数量的限制。在您的情况下,您可以在缓冲区已满之前添加最多200个字符串,任意长度,受程序可用总内存的限制。
  3. 正如Kumar指出的那样,你最好还是使用Java运行时库排队类,因为它们会为你处理同步,而Commons Collections类要求你自己锁定迭代器。