1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.io.hfile.bucket;
20
21
22 import java.util.Comparator;
23 import java.util.Map;
24 import java.util.Map.Entry;
25
26 import org.apache.hadoop.hbase.classification.InterfaceAudience;
27 import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
28 import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache.BucketEntry;
29
30 import com.google.common.collect.MinMaxPriorityQueue;
31
32
33
34
35
36
37
38
39
40
41
42
43 @InterfaceAudience.Private
44 public class CachedEntryQueue {
45
46 private MinMaxPriorityQueue<Map.Entry<BlockCacheKey, BucketEntry>> queue;
47
48 private long cacheSize;
49 private long maxSize;
50
51
52
53
54
55 public CachedEntryQueue(long maxSize, long blockSize) {
56 int initialSize = (int) (maxSize / blockSize);
57 if (initialSize == 0) {
58 initialSize++;
59 }
60 queue = MinMaxPriorityQueue.orderedBy(new Comparator<Map.Entry<BlockCacheKey, BucketEntry>>() {
61
62 public int compare(Entry<BlockCacheKey, BucketEntry> entry1,
63 Entry<BlockCacheKey, BucketEntry> entry2) {
64 return BucketEntry.COMPARATOR.compare(entry1.getValue(), entry2.getValue());
65 }
66
67 }).expectedSize(initialSize).create();
68 cacheSize = 0;
69 this.maxSize = maxSize;
70 }
71
72
73
74
75
76
77
78
79
80 public void add(Map.Entry<BlockCacheKey, BucketEntry> entry) {
81 if (cacheSize < maxSize) {
82 queue.add(entry);
83 cacheSize += entry.getValue().getLength();
84 } else {
85 BucketEntry head = queue.peek().getValue();
86 if (BucketEntry.COMPARATOR.compare(entry.getValue(), head) > 0) {
87 cacheSize += entry.getValue().getLength();
88 cacheSize -= head.getLength();
89 if (cacheSize > maxSize) {
90 queue.poll();
91 } else {
92 cacheSize += head.getLength();
93 }
94 queue.add(entry);
95 }
96 }
97 }
98
99
100
101
102
103 public Map.Entry<BlockCacheKey, BucketEntry> poll() {
104 return queue.poll();
105 }
106
107
108
109
110
111 public Map.Entry<BlockCacheKey, BucketEntry> pollLast() {
112 return queue.pollLast();
113 }
114
115
116
117
118
119 public long cacheSize() {
120 return cacheSize;
121 }
122 }