Skip to content

cache.put is first to be removed #124

@krm1312

Description

@krm1312

This may not be a bug, but, it is a difference between Guava and Caffeine. Basically, the most recent entry put into a cache appears to sometimes be the first one expired. Our actual use case is put from thread A, get from thread B, where thread B cannot actually build the object. If you run below, caffeine fails for a few in each run whereas guava does not.

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;

public class CaffeineTest {

    private static final int ITERATIONS = 10000;
    private static final int CACHE_SIZE = 1000;

    public static void main(String args[]) {
        testCaffeine();
        testGuava();
    }

    static void testCaffeine() {
        LoadingCache<Long, Object> cache = Caffeine.newBuilder()
                .maximumSize(CACHE_SIZE).build((k) -> null);
        for (long i=0; i<ITERATIONS; i++) {
            cache.put(i, i);
            if (null == cache.get(i)) {
                System.err.println("Caffeine: " + i + " was null");
            }
        }
    }

    static void testGuava() {
        com.google.common.cache.LoadingCache<Long, Object> cache = CacheBuilder.newBuilder()
                .maximumSize(CACHE_SIZE).build(new CacheLoader<Long, Object>() {
                    @Override
                    public Object load(Long key) throws Exception {
                        return null;
                    }
                });

        for (long i=0; i<ITERATIONS; i++) {
            cache.put(i, i);
            if (null == cache.getUnchecked(i)) {
                System.err.println("Guava: " + i + " was null");
            }
        }
    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions