source: josm/trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java@ 12855

Last change on this file since 12855 was 12855, checked in by bastiK, 7 years ago

see #15229 - add separate interface IBaseDirectories to look up pref, user data and cache dir

  • Property svn:eol-style set to native
File size: 11.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.cache;
3
4import java.io.File;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.nio.channels.FileLock;
8import java.util.Arrays;
9import java.util.Properties;
10import java.util.logging.Handler;
11import java.util.logging.Level;
12import java.util.logging.LogRecord;
13import java.util.logging.Logger;
14import java.util.logging.SimpleFormatter;
15
16import org.apache.commons.jcs.access.CacheAccess;
17import org.apache.commons.jcs.auxiliary.AuxiliaryCache;
18import org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory;
19import org.apache.commons.jcs.auxiliary.disk.behavior.IDiskCacheAttributes;
20import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheAttributes;
21import org.apache.commons.jcs.auxiliary.disk.block.BlockDiskCacheFactory;
22import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
23import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory;
24import org.apache.commons.jcs.engine.CompositeCacheAttributes;
25import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
26import org.apache.commons.jcs.engine.control.CompositeCache;
27import org.apache.commons.jcs.engine.control.CompositeCacheManager;
28import org.apache.commons.jcs.utils.serialization.StandardSerializer;
29import org.openstreetmap.josm.data.preferences.BooleanProperty;
30import org.openstreetmap.josm.data.preferences.IntegerProperty;
31import org.openstreetmap.josm.spi.preferences.Config;
32import org.openstreetmap.josm.tools.Logging;
33import org.openstreetmap.josm.tools.Utils;
34
35/**
36 * Wrapper class for JCS Cache. Sets some sane environment and returns instances of cache objects.
37 * Static configuration for now assumes some small LRU cache in memory and larger LRU cache on disk
38 *
39 * @author Wiktor Niesiobędzki
40 * @since 8168
41 */
42public final class JCSCacheManager {
43 private static volatile CompositeCacheManager cacheManager;
44 private static final long maxObjectTTL = -1;
45 private static final String PREFERENCE_PREFIX = "jcs.cache";
46 public static final BooleanProperty USE_BLOCK_CACHE = new BooleanProperty(PREFERENCE_PREFIX + ".use_block_cache", true);
47
48 private static final AuxiliaryCacheFactory DISK_CACHE_FACTORY =
49 USE_BLOCK_CACHE.get() ? new BlockDiskCacheFactory() : new IndexedDiskCacheFactory();
50 private static FileLock cacheDirLock;
51
52 /**
53 * default objects to be held in memory by JCS caches (per region)
54 */
55 public static final IntegerProperty DEFAULT_MAX_OBJECTS_IN_MEMORY = new IntegerProperty(PREFERENCE_PREFIX + ".max_objects_in_memory", 1000);
56
57 private static final Logger jcsLog;
58
59 static {
60 // raising logging level gives ~500x performance gain
61 // http://westsworld.dk/blog/2008/01/jcs-and-performance/
62 jcsLog = Logger.getLogger("org.apache.commons.jcs");
63 jcsLog.setLevel(Level.INFO);
64 jcsLog.setUseParentHandlers(false);
65 // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
66 Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
67 jcsLog.addHandler(new Handler() {
68 final SimpleFormatter formatter = new SimpleFormatter();
69
70 @Override
71 public void publish(LogRecord record) {
72 String msg = formatter.formatMessage(record);
73 if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
74 Logging.error(msg);
75 } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
76 Logging.warn(msg);
77 // downgrade INFO level to debug, as JCS is too verbose at INFO level
78 } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
79 Logging.debug(msg);
80 } else {
81 Logging.trace(msg);
82 }
83 }
84
85 @Override
86 public void flush() {
87 // nothing to be done on flush
88 }
89
90 @Override
91 public void close() {
92 // nothing to be done on close
93 }
94 });
95 }
96
97 private JCSCacheManager() {
98 // Hide implicit public constructor for utility classes
99 }
100
101 @SuppressWarnings("resource")
102 private static void initialize() throws IOException {
103 File cacheDir = new File(Config.getDirs().getCacheDirectory(), "jcs");
104
105 if (!cacheDir.exists() && !cacheDir.mkdirs())
106 throw new IOException("Cannot access cache directory");
107
108 File cacheDirLockPath = new File(cacheDir, ".lock");
109 if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
110 Logging.warn("Cannot create cache dir lock file");
111 }
112 cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();
113
114 if (cacheDirLock == null)
115 Logging.warn("Cannot lock cache directory. Will not use disk cache");
116
117 // this could be moved to external file
118 Properties props = new Properties();
119 // these are default common to all cache regions
120 // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
121 // CHECKSTYLE.OFF: SingleSpaceSeparator
122 props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
123 props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
124 props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
125 props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
126 props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
127 props.setProperty("jcs.default.elementattributes.IsEternal", "false");
128 props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
129 props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
130 props.setProperty("jcs.default.elementattributes.IsSpool", "true");
131 // CHECKSTYLE.ON: SingleSpaceSeparator
132 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
133 cm.configure(props);
134 cacheManager = cm;
135 }
136
137 /**
138 * Returns configured cache object for named cache region
139 * @param <K> key type
140 * @param <V> value type
141 * @param cacheName region name
142 * @return cache access object
143 * @throws IOException if directory is not found
144 */
145 public static <K, V> CacheAccess<K, V> getCache(String cacheName) throws IOException {
146 return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
147 }
148
149 /**
150 * Returns configured cache object with defined limits of memory cache and disk cache
151 * @param <K> key type
152 * @param <V> value type
153 * @param cacheName region name
154 * @param maxMemoryObjects number of objects to keep in memory
155 * @param maxDiskObjects maximum size of the objects stored on disk in kB
156 * @param cachePath path to disk cache. if null, no disk cache will be created
157 * @return cache access object
158 * @throws IOException if directory is not found
159 */
160 public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
161 throws IOException {
162 if (cacheManager != null)
163 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
164
165 synchronized (JCSCacheManager.class) {
166 if (cacheManager == null)
167 initialize();
168 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
169 }
170 }
171
172 @SuppressWarnings("unchecked")
173 private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
174 throws IOException {
175 CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
176
177 if (cachePath != null && cacheDirLock != null) {
178 IDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath, cacheName);
179 try {
180 if (cc.getAuxCaches().length == 0) {
181 cc.setAuxCaches(new AuxiliaryCache[]{DISK_CACHE_FACTORY.createCache(
182 diskAttributes, cacheManager, null, new StandardSerializer())});
183 }
184 } catch (IOException e) {
185 throw e;
186 } catch (Exception e) { // NOPMD
187 throw new IOException(e);
188 }
189 }
190 return new CacheAccess<>(cc);
191 }
192
193 /**
194 * Close all files to ensure, that all indexes and data are properly written
195 */
196 public static void shutdown() {
197 // use volatile semantics to get consistent object
198 CompositeCacheManager localCacheManager = cacheManager;
199 if (localCacheManager != null) {
200 localCacheManager.shutDown();
201 }
202 }
203
204 private static IDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath, String cacheName) {
205 IDiskCacheAttributes ret;
206 removeStaleFiles(cachePath + File.separator + cacheName, USE_BLOCK_CACHE.get() ? "_INDEX_v2" : "_BLOCK_v2");
207 String newCacheName = cacheName + (USE_BLOCK_CACHE.get() ? "_BLOCK_v2" : "_INDEX_v2");
208
209 if (USE_BLOCK_CACHE.get()) {
210 BlockDiskCacheAttributes blockAttr = new BlockDiskCacheAttributes();
211 /*
212 * BlockDiskCache never optimizes the file, so when file size is reduced, it will never be truncated to desired size.
213 *
214 * If for some mysterious reason, file size is greater than the value set in preferences, just use the whole file. If the user
215 * wants to reduce the file size, (s)he may just go to preferences and there it should be handled (by removing old file)
216 */
217 File diskCacheFile = new File(cachePath + File.separator + newCacheName + ".data");
218 if (diskCacheFile.exists()) {
219 blockAttr.setMaxKeySize((int) Math.max(maxDiskObjects, diskCacheFile.length()/1024));
220 } else {
221 blockAttr.setMaxKeySize(maxDiskObjects);
222 }
223 blockAttr.setBlockSizeBytes(4096); // use 4k blocks
224 ret = blockAttr;
225 } else {
226 IndexedDiskCacheAttributes indexAttr = new IndexedDiskCacheAttributes();
227 indexAttr.setMaxKeySize(maxDiskObjects);
228 ret = indexAttr;
229 }
230 ret.setDiskLimitType(IDiskCacheAttributes.DiskLimitType.SIZE);
231 File path = new File(cachePath);
232 if (!path.exists() && !path.mkdirs()) {
233 Logging.warn("Failed to create cache path: {0}", cachePath);
234 } else {
235 ret.setDiskPath(cachePath);
236 }
237 ret.setCacheName(newCacheName);
238
239 return ret;
240 }
241
242 private static void removeStaleFiles(String basePathPart, String suffix) {
243 deleteCacheFiles(basePathPart + suffix);
244 }
245
246 private static void deleteCacheFiles(String basePathPart) {
247 Utils.deleteFileIfExists(new File(basePathPart + ".key"));
248 Utils.deleteFileIfExists(new File(basePathPart + ".data"));
249 }
250
251 private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
252 CompositeCacheAttributes ret = new CompositeCacheAttributes();
253 ret.setMaxObjects(maxMemoryElements);
254 ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
255 return ret;
256 }
257}
Note: See TracBrowser for help on using the repository browser.