View Javadoc

1   /**
2    * Copyright 2008 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.io.hfile;
21  
22  import java.lang.ref.ReferenceQueue;
23  import java.lang.ref.SoftReference;
24  import java.nio.ByteBuffer;
25  import java.util.HashMap;
26  import java.util.Map;
27  
28  
29  /**
30   * Simple one RFile soft reference cache.
31   */
32  public class SimpleBlockCache implements BlockCache {
33    private static class Ref extends SoftReference<ByteBuffer> {
34      public String blockId;
35      public Ref(String blockId, ByteBuffer buf, ReferenceQueue q) {
36        super(buf, q);
37        this.blockId = blockId;
38      }
39    }
40    private Map<String,Ref> cache =
41      new HashMap<String,Ref>();
42  
43    private ReferenceQueue q = new ReferenceQueue();
44    public int dumps = 0;
45  
46    /**
47     * Constructor
48     */
49    public SimpleBlockCache() {
50      super();
51    }
52  
53    void processQueue() {
54      Ref r;
55      while ( (r = (Ref)q.poll()) != null) {
56        cache.remove(r.blockId);
57        dumps++;
58      }
59    }
60  
61    /**
62     * @return the size
63     */
64    public synchronized int size() {
65      processQueue();
66      return cache.size();
67    }
68  
69    public synchronized ByteBuffer getBlock(String blockName, boolean caching) {
70      processQueue(); // clear out some crap.
71      Ref ref = cache.get(blockName);
72      if (ref == null)
73        return null;
74      return ref.get();
75    }
76  
77    public synchronized void cacheBlock(String blockName, ByteBuffer buf) {
78      cache.put(blockName, new Ref(blockName, buf, q));
79    }
80  
81    public synchronized void cacheBlock(String blockName, ByteBuffer buf,
82        boolean inMemory) {
83      cache.put(blockName, new Ref(blockName, buf, q));
84    }
85  
86    public void shutdown() {
87      // noop
88    }
89  }