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

Last change on this file since 12765 was 12765, checked in by wiktorn, 7 years ago

Use tools.Logging instead of FeatureAdapter.getLogger

See: #15229

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