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

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

Hide implicit public constructor for utility classes

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