KeyCache.java

  1. /*
  2. Copyright (c) 2013 James Ahlborn

  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at

  6.     http://www.apache.org/licenses/LICENSE-2.0

  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */

  13. package com.healthmarketscience.jackcess.crypt.impl;

  14. import java.util.LinkedHashMap;
  15. import java.util.Map;

  16. /**
  17.  *
  18.  * @author James Ahlborn
  19.  */
  20. public abstract class KeyCache<K>
  21. {
  22.   private static final int MAX_KEY_CACHE_SIZE = 5;

  23.   private final KeyMap<K> _map = new KeyMap<K>();

  24.   protected KeyCache()
  25.   {
  26.   }

  27.   public K get(int pageNumber) {
  28.     Integer pageNumKey = pageNumber;
  29.     K key = _map.get(pageNumKey);
  30.     if(key == null) {
  31.       key = computeKey(pageNumber);
  32.       _map.put(pageNumKey, key);
  33.     }
  34.     return key;
  35.   }

  36.   protected abstract K computeKey(int pageNumber);


  37.   private static final class KeyMap<K> extends LinkedHashMap<Integer,K>
  38.   {
  39.     private static final long serialVersionUID = 0L;

  40.     private KeyMap() {
  41.       super(16, 0.75f, true);
  42.     }

  43.     @Override
  44.     protected boolean removeEldestEntry(Map.Entry<Integer,K> eldest) {
  45.       return size() > MAX_KEY_CACHE_SIZE;
  46.     }
  47.   }

  48. }