Cost weighted java cache

Viewed 113

I would like a caching library that manages based on cost weights.

I have a lot of different types of data with exact same structure to cache, but it the costs differ to cache each of different types, some are very cheap to retrieve back, some are expensive.

I want a way where I can add a weight to the caching library such it can efficiently cache to minimise cache misses.

1 Answers

Ehcache 2 had Policy.

Associate a weight to each value, make it implement your own interface, for example Weightable, and use:

public class WeightPolicy extends AbstractPolicy {
    @Override
    public String getName() {
        return "Weight";
    }

    @Override
    public boolean compare(Element element1, Element element2) {
        return ((Weightable) element1.getObjectValue()).getWeight() < ((Weightable) element2.getObjectValue()).getWeight();
    }
}

If the key and value are Serializable, you could use getSerializedSize(), although very inefficient.

return element1.getSerializedSize() < element2.getSerializedSize();
Related