View Javadoc
1   /**
2    *    Copyright 2009-2015 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.cache.decorators;
17  
18  import java.util.concurrent.locks.ReadWriteLock;
19  
20  import org.apache.ibatis.cache.Cache;
21  import org.apache.ibatis.logging.Log;
22  import org.apache.ibatis.logging.LogFactory;
23  
24  /**
25   * @author Clinton Begin
26   */
27  public class LoggingCache implements Cache {
28  
29    private Log log;  
30    private Cache delegate;
31    protected int requests = 0;
32    protected int hits = 0;
33  
34    public LoggingCache(Cache delegate) {
35      this.delegate = delegate;
36      this.log = LogFactory.getLog(getId());
37    }
38  
39    @Override
40    public String getId() {
41      return delegate.getId();
42    }
43  
44    @Override
45    public int getSize() {
46      return delegate.getSize();
47    }
48  
49    @Override
50    public void putObject(Object key, Object object) {
51      delegate.putObject(key, object);
52    }
53  
54    @Override
55    public Object getObject(Object key) {
56      requests++;
57      final Object value = delegate.getObject(key);
58      if (value != null) {
59        hits++;
60      }
61      if (log.isDebugEnabled()) {
62        log.debug("Cache Hit Ratio [" + getId() + "]: " + getHitRatio());
63      }
64      return value;
65    }
66  
67    @Override
68    public Object removeObject(Object key) {
69      return delegate.removeObject(key);
70    }
71  
72    @Override
73    public void clear() {
74      delegate.clear();
75    }
76  
77    @Override
78    public ReadWriteLock getReadWriteLock() {
79      return null;
80    }
81  
82    @Override
83    public int hashCode() {
84      return delegate.hashCode();
85    }
86  
87    @Override
88    public boolean equals(Object obj) {
89      return delegate.equals(obj);
90    }
91  
92    private double getHitRatio() {
93      return (double) hits / (double) requests;
94    }
95  
96  }