Justin
Justin

Reputation: 125

Is there a bounded non-blocking Collection in Java?

The only one I can find is the BoundedFIFOBuffer, which is deprecated. Any others?

Upvotes: 11

Views: 7041

Answers (4)

Justin Rudd
Justin Rudd

Reputation: 5364

I've been using Google Collections recently. I think you could have a Java Generics solution pretty easily with it. There is a class called ForwardingList which I think you could implement this idea pretty easily. Obviously not as easy as just using BoundedFifoBuffer (non-generic) or ArrayBlockingQueue.

final ArrayList<MyObject> realList = Lists.newArrayList();
final List<MyObject> list = new ForwardingList<MyObject>() {
    protected List<MyObject> delegate() {
        return realList;
    }

    public boolean add(MyObject obj) {
        if(delegate().size() > 100) return false;
        return delegate().add(obj);
    }
};

Upvotes: 2

Adamski
Adamski

Reputation: 54705

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

Upvotes: 14

Rich Seller
Rich Seller

Reputation: 84038

There are some bounded collections in Apache commons-collections, including a BoundedFifoBuffer.

In the same library, is also BoundedBuffer and CircularFifoBuffer

Upvotes: 3

skaffman
skaffman

Reputation: 403501

BoundedFIFOBuffer in Apache Commons Collections (which I assume is what you're referring to) is not deprecated, it has just moved packages. The original one in org.apache.commons.collections is deprecated, and has instead been moved to org.apache.commons.collections.buffer

Upvotes: 14

Related Questions