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

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

drop old stuff

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