All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.javers.repository.mongo.LatestSnapshotCache Maven / Gradle / Ivy

package org.javers.repository.mongo;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.Optional;
import org.javers.core.metamodel.object.CdoSnapshot;
import org.javers.core.metamodel.object.GlobalId;

import java.util.function.Function;

/**
 * @author bartosz.walacik
 */
class LatestSnapshotCache {
    private final Cache> cache;
    private final Function> source;
    private final boolean disabled;

    LatestSnapshotCache(int size, Function> source) {
        cache = CacheBuilder.newBuilder()
                .maximumSize(size)
                .build();

        this.source = source;
        this.disabled = size == 0;
    }

    Optional getLatest(GlobalId globalId) {
        if (disabled) {
            return source.apply(globalId);
        }

        Optional fromCache = cache.getIfPresent(globalId);

        if (fromCache != null) {
            return fromCache;
        }

        Optional fromDb = source.apply(globalId);
        cache.put(globalId, fromDb);
        return fromDb;
    }

    void put(CdoSnapshot cdoSnapshot) {
        if (disabled) {
            return;
        }
        cache.put(cdoSnapshot.getGlobalId(), Optional.of(cdoSnapshot));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy