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

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

code style - Useless parentheses around expressions should be removed to prevent any misunderstanding

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