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

Last change on this file since 12620 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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