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

Last change on this file since 9142 was 9142, checked in by wiktorn, 8 years ago

Revert [9064]. Move back to IndexedDiskCache

Closes: #12221, reopens: #11566

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