ConcurrentMapCache.java 6.6 KB
Newer Older
1
/*
2
 * Copyright 2002-2016 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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.springframework.cache.concurrent;

19 20 21
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
22
import java.util.concurrent.Callable;
23 24 25
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

26
import org.springframework.cache.support.AbstractValueAdaptingCache;
27
import org.springframework.core.serializer.support.SerializationDelegate;
28
import org.springframework.util.Assert;
29

30
/**
31 32
 * Simple {@link org.springframework.cache.Cache} implementation based on the
 * core JDK {@code java.util.concurrent} package.
33 34 35 36 37 38 39 40 41 42 43 44
 *
 * <p>Useful for testing or simple caching scenarios, typically in combination
 * with {@link org.springframework.cache.support.SimpleCacheManager} or
 * dynamically through {@link ConcurrentMapCacheManager}.
 *
 * <p><b>Note:</b> As {@link ConcurrentHashMap} (the default implementation used)
 * does not allow for {@code null} values to be stored, this class will replace
 * them with a predefined internal object. This behavior can be changed through the
 * {@link #ConcurrentMapCache(String, ConcurrentMap, boolean)} constructor.
 *
 * @author Costin Leau
 * @author Juergen Hoeller
45
 * @author Stephane Nicoll
46 47
 * @since 3.1
 */
48
public class ConcurrentMapCache extends AbstractValueAdaptingCache {
49 50 51 52 53

	private final String name;

	private final ConcurrentMap<Object, Object> store;

54 55
	private final SerializationDelegate serialization;

56 57 58 59 60 61

	/**
	 * Create a new ConcurrentMapCache with the specified name.
	 * @param name the name of the cache
	 */
	public ConcurrentMapCache(String name) {
62
		this(name, new ConcurrentHashMap<>(256), true);
63 64 65 66 67
	}

	/**
	 * Create a new ConcurrentMapCache with the specified name.
	 * @param name the name of the cache
J
Juergen Hoeller 已提交
68 69
	 * @param allowNullValues whether to accept and convert {@code null}
	 * values for this cache
70 71
	 */
	public ConcurrentMapCache(String name, boolean allowNullValues) {
72
		this(name, new ConcurrentHashMap<>(256), allowNullValues);
73 74 75 76
	}

	/**
	 * Create a new ConcurrentMapCache with the specified name and the
J
Juergen Hoeller 已提交
77
	 * given internal {@link ConcurrentMap} to use.
78 79
	 * @param name the name of the cache
	 * @param store the ConcurrentMap to use as an internal store
80
	 * @param allowNullValues whether to allow {@code null} values
81 82 83
	 * (adapting them to an internal null holder value)
	 */
	public ConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) {
84 85 86 87 88 89 90 91 92 93 94 95 96 97
		this(name, store, allowNullValues, null);
	}

	/**
	 * Create a new ConcurrentMapCache with the specified name and the
	 * given internal {@link ConcurrentMap} to use. If the
	 * {@link SerializationDelegate} is specified,
	 * {@link #isStoreByValue() store-by-value} is enabled
	 * @param name the name of the cache
	 * @param store the ConcurrentMap to use as an internal store
	 * @param allowNullValues whether to allow {@code null} values
	 * (adapting them to an internal null holder value)
	 * @param serialization the {@link SerializationDelegate} to use
	 * to serialize cache entry or {@code null} to store the reference
98
	 * @since 4.3
99 100 101 102
	 */
	protected ConcurrentMapCache(String name, ConcurrentMap<Object, Object> store,
			boolean allowNullValues, SerializationDelegate serialization) {

103
		super(allowNullValues);
104 105
		Assert.notNull(name, "Name must not be null");
		Assert.notNull(store, "Store must not be null");
106 107
		this.name = name;
		this.store = store;
108
		this.serialization = serialization;
109 110
	}

111

112 113 114 115
	/**
	 * Return whether this cache stores a copy of each entry ({@code true}) or
	 * a reference ({@code false}, default). If store by value is enabled, each
	 * entry in the cache must be serializable.
116
	 * @since 4.3
117 118
	 */
	public final boolean isStoreByValue() {
119
		return (this.serialization != null);
120
	}
121

122
	@Override
J
Juergen Hoeller 已提交
123
	public final String getName() {
124 125 126
		return this.name;
	}

127
	@Override
J
Juergen Hoeller 已提交
128
	public final ConcurrentMap<Object, Object> getNativeCache() {
129 130 131
		return this.store;
	}

132
	@Override
133 134
	protected Object lookup(Object key) {
		return this.store.get(key);
135 136
	}

137 138 139 140 141 142 143
	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(Object key, Callable<T> valueLoader) {
		if (this.store.containsKey(key)) {
			return (T) get(key).get();
		}
		else {
144
			return (T) fromStoreValue(this.store.computeIfAbsent(key, r -> {
145
				try {
146
					return toStoreValue(valueLoader.call());
147 148 149 150
				}
				catch (Exception ex) {
					throw new ValueRetrievalException(key, valueLoader, ex);
				}
151
			}));
152 153 154
		}
	}

155
	@Override
156 157 158 159
	public void put(Object key, Object value) {
		this.store.put(key, toStoreValue(value));
	}

160 161
	@Override
	public ValueWrapper putIfAbsent(Object key, Object value) {
162
		Object existing = this.store.putIfAbsent(key, toStoreValue(value));
163
		return toValueWrapper(existing);
164 165
	}

166
	@Override
167 168 169 170
	public void evict(Object key) {
		this.store.remove(key);
	}

171
	@Override
172 173 174 175
	public void clear() {
		this.store.clear();
	}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	@Override
	protected Object toStoreValue(Object userValue) {
		Object storeValue = super.toStoreValue(userValue);
		if (this.serialization != null) {
			try {
				return serializeValue(storeValue);
			}
			catch (Exception ex) {
				throw new IllegalArgumentException("Failed to serialize cache value '"
						+ userValue + "'. Does it implement Serializable?", ex);
			}
		}
		else {
			return storeValue;
		}
	}

	private Object serializeValue(Object storeValue) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			this.serialization.serialize(storeValue, out);
			return out.toByteArray();
		}
		finally {
			out.close();
		}
	}

	@Override
	protected Object fromStoreValue(Object storeValue) {
		if (this.serialization != null) {
			try {
				return super.fromStoreValue(deserializeValue(storeValue));
			}
			catch (Exception ex) {
				throw new IllegalArgumentException("Failed to deserialize cache value '" +
						storeValue + "'", ex);
			}
		}
		else {
			return super.fromStoreValue(storeValue);
		}

	}

	private Object deserializeValue(Object storeValue) throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream((byte[]) storeValue);
		try {
			return this.serialization.deserialize(in);
		}
		finally {
			in.close();
		}
	}

231
}