org.exoplatform.commons.utils
Class BoundedBuffer<T>

java.lang.Object
  extended by org.exoplatform.commons.utils.BoundedBuffer<T>
All Implemented Interfaces:
java.lang.Iterable<T>
Direct Known Subclasses:
LongSampler

public class BoundedBuffer<T>
extends java.lang.Object
implements java.lang.Iterable<T>

A thread safe bounded buffer.

The idea of this class is that it retains only the last elements added to the buffer up to a determined size, but it is possible to make snapshot of the buffer elements and iterate over them with a neglectable impact on synchronization.

It maintains a linked list. When a new element is added, the first element will have for successor that new element. If the number of elements is greater than the max size then the last element is discarded.

When a snapshot for iteration is required, the class only needs to keep a reference to the last element of the list and keep also the actual size of the list. The copy is made in an atomic manner for consistency. Note that this class expose only a notion of iterator to its client instead of a notion of list as iterator have a notion of being short lived objects. Indeed keeping a reference on an iterator would create a memory leak and so this class must be used with caution.

Version:
$Revision$
Author:
Julien Viet

Constructor Summary
BoundedBuffer(int maxSize)
           
 
Method Summary
 void add(T t)
          Add an element to the buffer.
 int getMaxSize()
           
 int getSize()
           
 java.util.Iterator<T> iterator()
          Make a snapshot of the buffer and iterate over the elements.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

BoundedBuffer

public BoundedBuffer(int maxSize)
Method Detail

getMaxSize

public int getMaxSize()

getSize

public int getSize()

add

public void add(T t)
Add an element to the buffer.

Parameters:
t - the element to add

iterator

public java.util.Iterator<T> iterator()
Make a snapshot of the buffer and iterate over the elements. It is important to not keep reference on an iterator returned by this method otherwise it could create a memory leak.

Specified by:
iterator in interface java.lang.Iterable<T>
Returns:
an iterator over the elements


Copyright © 2010 eXo Platform SAS. All Rights Reserved.