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

org.gradle.cache.internal.DefaultFileContentCacheFactory Maven / Gradle / Ivy

There is a newer version: 8.6
Show newest version
/*
 * Copyright 2017 the original author or authors.
 *
 * 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 org.gradle.cache.internal;

import org.gradle.cache.CacheRepository;
import org.gradle.cache.FileLockManager;
import org.gradle.cache.PersistentCache;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.cache.PersistentIndexedCacheParameters;
import org.gradle.internal.Cast;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.execution.OutputChangeListener;
import org.gradle.internal.hash.HashCode;
import org.gradle.internal.serialize.HashCodeSerializer;
import org.gradle.internal.serialize.Serializer;
import org.gradle.internal.vfs.VirtualFileSystem;

import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;

public class DefaultFileContentCacheFactory implements FileContentCacheFactory, Closeable {
    private final ListenerManager listenerManager;
    private final VirtualFileSystem virtualFileSystem;
    private final InMemoryCacheDecoratorFactory inMemoryCacheDecoratorFactory;
    private final PersistentCache cache;
    private final HashCodeSerializer hashCodeSerializer = new HashCodeSerializer();
    private final ConcurrentMap> caches = new ConcurrentHashMap<>();

    public DefaultFileContentCacheFactory(ListenerManager listenerManager, VirtualFileSystem virtualFileSystem, CacheRepository cacheRepository, InMemoryCacheDecoratorFactory inMemoryCacheDecoratorFactory, @Nullable Object scope) {
        this.listenerManager = listenerManager;
        this.virtualFileSystem = virtualFileSystem;
        this.inMemoryCacheDecoratorFactory = inMemoryCacheDecoratorFactory;
        cache = cacheRepository
            .cache(scope, "fileContent")
            .withDisplayName("file content cache")
            .withLockOptions(mode(FileLockManager.LockMode.OnDemand)) // Lock on demand
            .open();
    }

    @Override
    public void close() throws IOException {
        cache.close();
    }

    @Override
    public  FileContentCache newCache(String name, int normalizedCacheSize, final Calculator calculator, Serializer serializer) {
        PersistentIndexedCacheParameters parameters = PersistentIndexedCacheParameters.of(name, hashCodeSerializer, serializer)
            .withCacheDecorator(inMemoryCacheDecoratorFactory.decorator(normalizedCacheSize, true));
        PersistentIndexedCache store = cache.createCache(parameters);

        DefaultFileContentCache cache = Cast.uncheckedCast(caches.get(name));
        if (cache == null) {
            cache = new DefaultFileContentCache<>(name, virtualFileSystem, store, calculator);
            DefaultFileContentCache existing = Cast.uncheckedCast(caches.putIfAbsent(name, cache));
            if (existing == null) {
                listenerManager.addListener(cache);
            } else {
                cache = existing;
            }
        }

        cache.assertStoredIn(store);
        return cache;
    }

    /**
     * Maintains 2 levels of in-memory caching. The first, fast, level indexes on file path and contains the value that is very likely to reflect the current contents of the file. This first cache is invalidated whenever any task actions are run.
     *
     * The second level indexes on the hash of file content and contains the value that was calculated from a file with the given hash.
     */
    private static class DefaultFileContentCache implements FileContentCache, OutputChangeListener {
        private final Map locationCache = new ConcurrentHashMap<>();
        private final String name;
        private final VirtualFileSystem virtualFileSystem;
        private final PersistentIndexedCache contentCache;
        private final Calculator calculator;

        DefaultFileContentCache(String name, VirtualFileSystem virtualFileSystem, PersistentIndexedCache contentCache, Calculator calculator) {
            this.name = name;
            this.virtualFileSystem = virtualFileSystem;
            this.contentCache = contentCache;
            this.calculator = calculator;
        }

        @Override
        public void beforeOutputChange() {
            // A very dumb strategy for invalidating cache
            locationCache.clear();
        }

        @Override
        public void beforeOutputChange(Iterable affectedOutputPaths) {
            beforeOutputChange();
        }

        @Override
        public V get(File file) {
            return locationCache.computeIfAbsent(file,
                location -> virtualFileSystem.readRegularFileContentHash(
                    location.getAbsolutePath(),
                    contentHash -> contentCache.get(contentHash, key -> calculator.calculate(location, true))
                ).orElseGet(
                    () -> calculator.calculate(location, false)
                ));
        }

        private void assertStoredIn(PersistentIndexedCache store) {
            if (this.contentCache != store) {
                throw new IllegalStateException("Cache " + name + " cannot be recreated with different parameters");
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy