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

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

checkstyle: enable relevant whitespace checks and fix them

File size: 8.9 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.text.MessageFormat;
9import java.util.Properties;
10import java.util.logging.Handler;
11import java.util.logging.Level;
12import java.util.logging.LogRecord;
13import java.util.logging.Logger;
14
15import org.apache.commons.jcs.access.CacheAccess;
16import org.apache.commons.jcs.auxiliary.AuxiliaryCache;
17import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCache;
18import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
19import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory;
20import org.apache.commons.jcs.engine.CompositeCacheAttributes;
21import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
22import org.apache.commons.jcs.engine.control.CompositeCache;
23import org.apache.commons.jcs.engine.control.CompositeCacheManager;
24import org.apache.commons.jcs.utils.serialization.StandardSerializer;
25import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.data.preferences.IntegerProperty;
28
29/**
30 * @author Wiktor Niesiobędzki
31 *
32 * Wrapper class for JCS Cache. Sets some sane environment and returns instances of cache objects.
33 * Static configuration for now assumes some small LRU cache in memory and larger LRU cache on disk
34 * @since 8168
35 */
36public class JCSCacheManager {
37 private static final Logger log = FeatureAdapter.getLogger(JCSCacheManager.class.getCanonicalName());
38
39 private static volatile CompositeCacheManager cacheManager = null;
40 private static long maxObjectTTL = Long.MAX_VALUE;
41 private static final String PREFERENCE_PREFIX = "jcs.cache";
42 private static final IndexedDiskCacheFactory diskCacheFactory = new IndexedDiskCacheFactory();
43 private static FileLock cacheDirLock = null;
44
45 /**
46 * default objects to be held in memory by JCS caches (per region)
47 */
48 public static final IntegerProperty DEFAULT_MAX_OBJECTS_IN_MEMORY = new IntegerProperty(PREFERENCE_PREFIX + ".max_objects_in_memory", 1000);
49
50 private JCSCacheManager() {
51 // Hide implicit public constructor for utility classes
52 }
53
54 @SuppressWarnings("resource")
55 private static void initialize() throws IOException {
56 File cacheDir = new File(Main.pref.getCacheDirectory(), "jcs");
57
58 if (!cacheDir.exists() && !cacheDir.mkdirs())
59 throw new IOException("Cannot access cache directory");
60
61 File cacheDirLockPath = new File(cacheDir, ".lock");
62 if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
63 log.log(Level.WARNING, "Cannot create cache dir lock file");
64 }
65 cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();
66
67 if (cacheDirLock == null)
68 log.log(Level.WARNING, "Cannot lock cache directory. Will not use disk cache");
69
70 // raising logging level gives ~500x performance gain
71 // http://westsworld.dk/blog/2008/01/jcs-and-performance/
72 Logger jcsLog = Logger.getLogger("org.apache.commons.jcs");
73 jcsLog.setLevel(Level.INFO);
74 jcsLog.setUseParentHandlers(false);
75 // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
76 jcsLog.addHandler(new Handler() {
77 @Override
78 public void publish(LogRecord record) {
79 String msg = MessageFormat.format(record.getMessage(), record.getParameters());
80 if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
81 Main.error(msg);
82 } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
83 Main.warn(msg);
84 // downgrade INFO level to debug, as JCS is too verbose at INFO level
85 } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
86 Main.debug(msg);
87 } else {
88 Main.trace(msg);
89 }
90 }
91
92 @Override
93 public void flush() {
94 }
95
96 @Override
97 public void close() {
98 }
99 });
100
101 // this could be moved to external file
102 Properties props = new Properties();
103 // these are default common to all cache regions
104 // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
105 props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
106 props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
107 props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
108 props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
109 props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
110 props.setProperty("jcs.default.elementattributes.IsEternal", "false");
111 props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
112 props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
113 props.setProperty("jcs.default.elementattributes.IsSpool", "true");
114 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
115 cm.configure(props);
116 cacheManager = cm;
117 }
118
119 /**
120 * Returns configured cache object for named cache region
121 * @param cacheName region name
122 * @return cache access object
123 * @throws IOException if directory is not found
124 */
125 public static <K, V> CacheAccess<K, V> getCache(String cacheName) throws IOException {
126 return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
127 }
128
129 /**
130 * Returns configured cache object with defined limits of memory cache and disk cache
131 * @param cacheName region name
132 * @param maxMemoryObjects number of objects to keep in memory
133 * @param maxDiskObjects number of objects to keep on disk (if cachePath provided)
134 * @param cachePath path to disk cache. if null, no disk cache will be created
135 * @return cache access object
136 * @throws IOException if directory is not found
137 */
138 public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
139 throws IOException {
140 if (cacheManager != null)
141 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
142
143 synchronized (JCSCacheManager.class) {
144 if (cacheManager == null)
145 initialize();
146 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
147 }
148 }
149
150 @SuppressWarnings("unchecked")
151 private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
152 CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
153
154 if (cachePath != null && cacheDirLock != null) {
155 IndexedDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath);
156 diskAttributes.setCacheName(cacheName);
157 IndexedDiskCache<K, V> diskCache = diskCacheFactory.createCache(diskAttributes, cacheManager, null, new StandardSerializer());
158
159 cc.setAuxCaches(new AuxiliaryCache[]{diskCache});
160 }
161 return new CacheAccess<K, V>(cc);
162 }
163
164 /**
165 * Close all files to ensure, that all indexes and data are properly written
166 */
167 public static void shutdown() {
168 // use volatile semantics to get consistent object
169 CompositeCacheManager localCacheManager = cacheManager;
170 if (localCacheManager != null) {
171 localCacheManager.shutDown();
172 }
173 }
174
175 private static IndexedDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath) {
176 IndexedDiskCacheAttributes ret = new IndexedDiskCacheAttributes();
177 ret.setMaxKeySize(maxDiskObjects);
178 if (cachePath != null) {
179 File path = new File(cachePath);
180 if (!path.exists() && !path.mkdirs()) {
181 log.log(Level.WARNING, "Failed to create cache path: {0}", cachePath);
182 } else {
183 ret.setDiskPath(path);
184 }
185 }
186 return ret;
187 }
188
189 private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
190 CompositeCacheAttributes ret = new CompositeCacheAttributes();
191 ret.setMaxObjects(maxMemoryElements);
192 ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
193 return ret;
194 }
195}
Note: See TracBrowser for help on using the repository browser.