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

Last change on this file since 8659 was 8659, checked in by wiktorn, 9 years ago

More performance improvements

  • Use one MemoryTileCache instance per multiple layers. This results in smaller memory footprint when working with many layers
  • fix default maximum TimeToLive in JCS
  • TemplatedWMSTileSource now caches degreesPerZoom, so it's not computed on every request
  • Property svn:eol-style set to native
File size: 9.3 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.AuxiliaryCacheFactory;
18import org.apache.commons.jcs.auxiliary.disk.behavior.IDiskCacheAttributes;
19import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes;
20import org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory;
21import org.apache.commons.jcs.engine.CompositeCacheAttributes;
22import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
23import org.apache.commons.jcs.engine.control.CompositeCache;
24import org.apache.commons.jcs.engine.control.CompositeCacheManager;
25import org.apache.commons.jcs.utils.serialization.StandardSerializer;
26import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.data.preferences.IntegerProperty;
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 * @since 8168
36 */
37public final 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 = -1;
42 private static final String PREFERENCE_PREFIX = "jcs.cache";
43 private static final AuxiliaryCacheFactory 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 private JCSCacheManager() {
52 // Hide implicit public constructor for utility classes
53 }
54
55 @SuppressWarnings("resource")
56 private static void initialize() throws IOException {
57 File cacheDir = new File(Main.pref.getCacheDirectory(), "jcs");
58
59 if (!cacheDir.exists() && !cacheDir.mkdirs())
60 throw new IOException("Cannot access cache directory");
61
62 File cacheDirLockPath = new File(cacheDir, ".lock");
63 if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
64 LOG.log(Level.WARNING, "Cannot create cache dir lock file");
65 }
66 cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();
67
68 if (cacheDirLock == null)
69 LOG.log(Level.WARNING, "Cannot lock cache directory. Will not use disk cache");
70
71 // raising logging level gives ~500x performance gain
72 // http://westsworld.dk/blog/2008/01/jcs-and-performance/
73 final Logger jcsLog = Logger.getLogger("org.apache.commons.jcs");
74 jcsLog.setLevel(Level.INFO);
75 jcsLog.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 // nothing to be done on flush
96 }
97
98 @Override
99 public void close() {
100 // nothing to be done on close
101 }
102 });
103
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", 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 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
118 cm.configure(props);
119 cacheManager = cm;
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 maximum size of the objects stored on disk in kB
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)
142 throws IOException {
143 if (cacheManager != null)
144 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
145
146 synchronized (JCSCacheManager.class) {
147 if (cacheManager == null)
148 initialize();
149 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
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 IDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath);
159 diskAttributes.setCacheName(cacheName);
160 try {
161 if (cc.getAuxCaches().length == 0) {
162 AuxiliaryCache<K, V> diskCache = diskCacheFactory.createCache(diskAttributes, cacheManager, null, new StandardSerializer());
163 cc.setAuxCaches(new AuxiliaryCache[]{diskCache});
164 }
165 } catch (Exception e) {
166 throw new RuntimeException(e);
167 }
168 }
169 return new CacheAccess<K, V>(cc);
170 }
171
172 /**
173 * Close all files to ensure, that all indexes and data are properly written
174 */
175 public static void shutdown() {
176 // use volatile semantics to get consistent object
177 CompositeCacheManager localCacheManager = cacheManager;
178 if (localCacheManager != null) {
179 localCacheManager.shutDown();
180 }
181 }
182
183 private static IDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath) {
184 IndexedDiskCacheAttributes ret = new IndexedDiskCacheAttributes();
185 ret.setDiskLimitType(IDiskCacheAttributes.DiskLimitType.SIZE);
186 ret.setMaxKeySize(maxDiskObjects);
187 if (cachePath != null) {
188 File path = new File(cachePath);
189 if (!path.exists() && !path.mkdirs()) {
190 LOG.log(Level.WARNING, "Failed to create cache path: {0}", cachePath);
191 } else {
192 ret.setDiskPath(path);
193 }
194 }
195 return ret;
196 }
197
198 private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
199 CompositeCacheAttributes ret = new CompositeCacheAttributes();
200 ret.setMaxObjects(maxMemoryElements);
201 ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
202 return ret;
203 }
204}
Note: See TracBrowser for help on using the repository browser.