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

Last change on this file since 9786 was 9246, checked in by Don-vip, 8 years ago

javadoc update

  • Property svn:eol-style set to native
File size: 9.4 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 <K> key type
127 * @param <V> value type
128 * @param cacheName region name
129 * @return cache access object
130 * @throws IOException if directory is not found
131 */
132 public static <K, V> CacheAccess<K, V> getCache(String cacheName) throws IOException {
133 return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
134 }
135
136 /**
137 * Returns configured cache object with defined limits of memory cache and disk cache
138 * @param <K> key type
139 * @param <V> value type
140 * @param cacheName region name
141 * @param maxMemoryObjects number of objects to keep in memory
142 * @param maxDiskObjects maximum size of the objects stored on disk in kB
143 * @param cachePath path to disk cache. if null, no disk cache will be created
144 * @return cache access object
145 * @throws IOException if directory is not found
146 */
147 public static <K, V> CacheAccess<K, V> getCache(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
148 throws IOException {
149 if (cacheManager != null)
150 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
151
152 synchronized (JCSCacheManager.class) {
153 if (cacheManager == null)
154 initialize();
155 return getCacheInner(cacheName, maxMemoryObjects, maxDiskObjects, cachePath);
156 }
157 }
158
159 @SuppressWarnings("unchecked")
160 private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
161 CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
162
163 if (cachePath != null && cacheDirLock != null) {
164 IDiskCacheAttributes diskAttributes = getDiskCacheAttributes(maxDiskObjects, cachePath);
165 diskAttributes.setCacheName(cacheName);
166 try {
167 if (cc.getAuxCaches().length == 0) {
168 AuxiliaryCache<K, V> diskCache = diskCacheFactory.createCache(diskAttributes, cacheManager, null, new StandardSerializer());
169 cc.setAuxCaches(new AuxiliaryCache[]{diskCache});
170 }
171 } catch (Exception e) {
172 throw new RuntimeException(e);
173 }
174 }
175 return new CacheAccess<>(cc);
176 }
177
178 /**
179 * Close all files to ensure, that all indexes and data are properly written
180 */
181 public static void shutdown() {
182 // use volatile semantics to get consistent object
183 CompositeCacheManager localCacheManager = cacheManager;
184 if (localCacheManager != null) {
185 localCacheManager.shutDown();
186 }
187 }
188
189 private static IDiskCacheAttributes getDiskCacheAttributes(int maxDiskObjects, String cachePath) {
190 IndexedDiskCacheAttributes ret = new IndexedDiskCacheAttributes();
191 ret.setDiskLimitType(IDiskCacheAttributes.DiskLimitType.SIZE);
192 ret.setMaxKeySize(maxDiskObjects);
193 if (cachePath != null) {
194 File path = new File(cachePath);
195 if (!path.exists() && !path.mkdirs()) {
196 LOG.log(Level.WARNING, "Failed to create cache path: {0}", cachePath);
197 } else {
198 ret.setDiskPath(path);
199 }
200 }
201 return ret;
202 }
203
204 private static CompositeCacheAttributes getCacheAttributes(int maxMemoryElements) {
205 CompositeCacheAttributes ret = new CompositeCacheAttributes();
206 ret.setMaxObjects(maxMemoryElements);
207 ret.setDiskUsagePattern(DiskUsagePattern.UPDATE);
208 return ret;
209 }
210}
Note: See TracBrowser for help on using the repository browser.