1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.client;
21
22 import org.apache.hadoop.conf.Configuration;
23 import org.apache.hadoop.hbase.HBaseConfiguration;
24 import org.apache.hadoop.hbase.util.Bytes;
25
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.LinkedList;
29 import java.util.Map;
30 import java.util.Queue;
31
32
33
34
35
36
37
38
39
40
41
42
43 public class HTablePool {
44 private final Map<String, LinkedList<HTableInterface>> tables =
45 Collections.synchronizedMap(new HashMap<String, LinkedList<HTableInterface>>());
46 private final Configuration config;
47 private final int maxSize;
48 private HTableInterfaceFactory tableFactory = new HTableFactory();
49
50
51
52
53 public HTablePool() {
54 this(HBaseConfiguration.create(), Integer.MAX_VALUE);
55 }
56
57
58
59
60
61
62 public HTablePool(Configuration config, int maxSize) {
63 this.config = config;
64 this.maxSize = maxSize;
65 }
66
67 public HTablePool(Configuration config, int maxSize, HTableInterfaceFactory tableFactory) {
68 this.config = config;
69 this.maxSize = maxSize;
70 this.tableFactory = tableFactory;
71 }
72
73
74
75
76
77
78
79
80
81 public HTableInterface getTable(String tableName) {
82 LinkedList<HTableInterface> queue = tables.get(tableName);
83 if(queue == null) {
84 queue = new LinkedList<HTableInterface>();
85 tables.put(tableName, queue);
86 return createHTable(tableName);
87 }
88 HTableInterface table;
89 synchronized(queue) {
90 table = queue.poll();
91 }
92 if(table == null) {
93 return createHTable(tableName);
94 }
95 return table;
96 }
97
98
99
100
101
102
103
104
105
106 public HTableInterface getTable(byte [] tableName) {
107 return getTable(Bytes.toString(tableName));
108 }
109
110
111
112
113
114
115
116
117 public void putTable(HTableInterface table) {
118 LinkedList<HTableInterface> queue = tables.get(Bytes.toString(table.getTableName()));
119 synchronized(queue) {
120 if(queue.size() >= maxSize) return;
121 queue.add(table);
122 }
123 }
124
125 protected HTableInterface createHTable(String tableName) {
126 return this.tableFactory.createHTableInterface(config, Bytes.toBytes(tableName));
127 }
128
129
130
131
132
133
134
135
136
137
138 public void closeTablePool(final String tableName) {
139 Queue<HTableInterface> queue = tables.get(tableName);
140 synchronized (queue) {
141 HTableInterface table = queue.poll();
142 while (table != null) {
143 this.tableFactory.releaseHTableInterface(table);
144 table = queue.poll();
145 }
146 }
147
148 }
149
150
151
152
153
154
155 public void closeTablePool(final byte[] tableName) {
156 closeTablePool(Bytes.toString(tableName));
157 }
158
159 int getCurrentPoolSize(String tableName) {
160 Queue<HTableInterface> queue = tables.get(tableName);
161 synchronized(queue) {
162 return queue.size();
163 }
164 }
165 }