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

io.fluxcapacitor.javaclient.persisting.caching.DefaultCache Maven / Gradle / Ivy

There is a newer version: 0.1015.0
Show newest version
/*
 * Copyright (c) 2016-2017 Flux Capacitor.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.fluxcapacitor.javaclient.persisting.caching;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;

@Slf4j
public class DefaultCache implements Cache {

    private final LinkedHashMap cache;

    public DefaultCache() {
        this(1_000);
    }
    
    public DefaultCache(int maxSize) {
        cache = new LinkedHashMap() {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > maxSize;
            }
        };
    }

    @Override
    public void put(String id, Object value) {
        cache.put(id, value);
    }

    @Override
    @SneakyThrows
    public  T get(String id, Function mappingFunction) {
        T result = getIfPresent(id);
        if (result == null) {
            result = mappingFunction.apply(id);
            cache.putIfAbsent(id, result);
        }
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public  T getIfPresent(String id) {
        return (T) cache.get(id);
    }

    @Override
    public void invalidate(String id) {
        cache.remove(id);
    }

    @Override
    public void invalidateAll() {
        cache.clear();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy