001: package org.shiftone.cache.decorator.stat;
002:
003: import org.shiftone.cache.Cache;
004: import org.shiftone.cache.util.Log;
005:
006: import java.util.Date;
007:
008: /**
009: * Class StatCache
010: *
011: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
012: * @version $Revision: 1.8 $
013: */
014: public class StatCache implements Cache {
015:
016: private static final Log LOG = new Log(StatCache.class);
017: private final Cache cache;
018: private final String name;
019: private final Date createDate = new Date();
020: private Sequence getCount = new Sequence();
021: private Sequence addCount = new Sequence();
022: private Sequence removeCount = new Sequence();
023: private Sequence missCount = new Sequence();
024: private Sequence hitCount = new Sequence();
025: private int maxSize = 0;
026:
027: public StatCache(String name, Cache cache) {
028: this .name = name;
029: this .cache = cache;
030: }
031:
032: private synchronized void updateMaxSize() {
033: int size = cache.size();
034: if (size > maxSize) {
035: maxSize = size;
036: }
037: }
038:
039: /**
040: * Method addObject
041: */
042: public void addObject(Object userKey, Object cacheObject) {
043: addCount.increment();
044: cache.addObject(userKey, cacheObject);
045: updateMaxSize();
046: }
047:
048: /**
049: * Method getObject
050: */
051: public Object getObject(Object key) {
052:
053: Object object = cache.getObject(key);
054:
055: getCount.increment();
056:
057: if (object == null) {
058: missCount.increment();
059: } else {
060: hitCount.increment();
061: }
062:
063: return object;
064: }
065:
066: /**
067: * Method remove
068: */
069: public void remove(Object key) {
070: removeCount.increment();
071: cache.remove(key);
072: }
073:
074: /**
075: * Method size
076: */
077: public int size() {
078: return cache.size();
079: }
080:
081: /**
082: * Method clear
083: */
084: public void clear() {
085: cache.clear();
086: }
087:
088: /**
089: * Method getHitRatio is the ratio of hits to tries.
090: * hitCount / (hitCount + missCount)
091: */
092: public double getHitRatio() {
093:
094: long tryCount = hitCount.getValue() + missCount.getValue();
095:
096: return (tryCount == 0) ? 0 : (hitCount.getValue() / tryCount);
097: }
098:
099: /**
100: * Method toString
101: */
102: public String toString() {
103: return "StatCache->" + cache;
104: }
105:
106: public void printStats() {
107:
108: LOG
109: .info("Stats : " + name + " - " + cache + " - "
110: + createDate);
111: LOG.info("\t:\tgetCount = " + getCount);
112: LOG.info("\t:\taddCount = " + addCount);
113: LOG.info("\t:\tremoveCount = " + removeCount);
114: LOG.info("\t:\tmissCount = " + missCount);
115: LOG.info("\t:\tgetCount = " + getCount);
116: LOG.info("\t:\thitCount = " + hitCount);
117: }
118: }
|