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