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

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

fix squid:RedundantThrowsDeclarationCheck + consistent Javadoc for exceptions

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