001/**
002 * Copyright (C) 2006-2019 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.api.service.cache;
017
018import java.util.function.Supplier;
019
020/**
021 * Framework service injectable in components or services methods
022 * to handle local caching.
023 * Useful for actions when deployed in a long running instance
024 * when actions are costly.
025 */
026public interface LocalCache {
027
028    /**
029     * Read or compute and save a value for a determined duration.
030     *
031     * @param key the cache key, must be unique accross the server.
032     * @param timeoutMs the cache duration.
033     * @param supplier the value provider if the cache get does a miss.
034     * @param <T> the type of data to access/cache.
035     * @return the cached or newly computed value.
036     */
037    <T> T computeIfAbsent(String key, long timeoutMs, Supplier<T> supplier);
038
039    /**
040     * Default the timeout to {@literal Integer.MAX_VALUE}.
041     *
042     * @param key the cache key, must be unique accross the server.
043     * @param supplier the value provider if the cache get does a miss.
044     * @param <T> the type of data to access/cache.
045     * @return the cached or newly computed - and cached indefinitively - value.
046     */
047    default <T> T computeIfAbsent(String key, Supplier<T> supplier) {
048        return computeIfAbsent(key, Integer.MAX_VALUE, supplier);
049    }
050}