001/*
002 * Copyright 2002-2020 the original author or authors.
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 *      https://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 */
016
017package org.springframework.cache.support;
018
019import java.util.Collection;
020import java.util.Collections;
021import java.util.LinkedHashSet;
022import java.util.Set;
023import java.util.concurrent.ConcurrentHashMap;
024import java.util.concurrent.ConcurrentMap;
025
026import org.springframework.cache.Cache;
027import org.springframework.cache.CacheManager;
028
029/**
030 * A basic, no operation {@link CacheManager} implementation suitable
031 * for disabling caching, typically used for backing cache declarations
032 * without an actual backing store.
033 *
034 * <p>Will simply accept any items into the cache not actually storing them.
035 *
036 * @author Costin Leau
037 * @author Stephane Nicoll
038 * @since 3.1
039 * @see NoOpCache
040 */
041public class NoOpCacheManager implements CacheManager {
042
043        private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>(16);
044
045        private final Set<String> cacheNames = new LinkedHashSet<String>(16);
046
047
048        /**
049         * This implementation always returns a {@link Cache} implementation that will not store items.
050         * Additionally, the request cache will be remembered by the manager for consistency.
051         */
052        @Override
053        public Cache getCache(String name) {
054                Cache cache = this.caches.get(name);
055                if (cache == null) {
056                        this.caches.putIfAbsent(name, new NoOpCache(name));
057                        synchronized (this.cacheNames) {
058                                this.cacheNames.add(name);
059                        }
060                }
061
062                return this.caches.get(name);
063        }
064
065        /**
066         * This implementation returns the name of the caches previously requested.
067         */
068        @Override
069        public Collection<String> getCacheNames() {
070                synchronized (this.cacheNames) {
071                        return Collections.unmodifiableSet(this.cacheNames);
072                }
073        }
074
075}