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

com.facebook.airlift.concurrent.ThreadLocalCache Maven / Gradle / Ivy

The newest version!
/*
 * 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 com.facebook.airlift.concurrent;

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

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

/**
 * Provides a ThreadLocal cache with a maximum cache size per thread.
 * Values must not be null.
 *
 * @param  cache key type
 * @param  cache value type
 */
public final class ThreadLocalCache
{
    @SuppressWarnings("ThreadLocalNotStaticFinal")
    private final ThreadLocal> cache;
    private final Function loader;

    public ThreadLocalCache(int maxSizePerThread, Function loader)
    {
        checkArgument(maxSizePerThread > 0, "max size must be greater than zero");
        this.cache = ThreadLocal.withInitial(() -> new BoundedMap(maxSizePerThread));
        this.loader = requireNonNull(loader, "loader is null");
    }

    public V get(K key)
    {
        V value = cache.get().computeIfAbsent(key, loader);
        return requireNonNull(value, "loader returned null value");
    }

    @SuppressWarnings("CloneableClassWithoutClone")
    private static class BoundedMap
            extends LinkedHashMap
    {
        private final int maxSize;

        public BoundedMap(int maxSize)
        {
            this.maxSize = maxSize;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry eldest)
        {
            return size() > maxSize;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy