HTablePool 连接池源码分析

 public class HTablePool {
 //存放多个htable的ConcurrentMap,这里用ConcurrentMap是为了线程安全
 //LinkedList放的是同一hatable多个对象的链表
 private final ConcurrentMap<String, LinkedList<HTableInterface>> tables =new ConcurrentHashMap<String, LinkedList<HTableInterface>>();
 private final Configuration config;
 //设置统一htable的最大值
 private final int maxSize;
 private final HTableInterfaceFactory tableFactory;
 /**
 * 默认构造方法,没有表最大值限制
 */
 public HTablePool() {
  this(HBaseConfiguration.create(), Integer.MAX_VALUE);
 }
 
 /**
 * 带参构造方法不啰嗦
 */
 public HTablePool(final Configuration config, final int maxSize) {
  this(config, maxSize, null);
 }
 public HTablePool(final Configuration config, final int maxSize,
 final HTableInterfaceFactory tableFactory) {
 this.config = config == null? new Configuration(): new Configuration(config);
 this.maxSize = maxSize;
 this.tableFactory = tableFactory == null? new HTableFactory(): tableFactory;
 }
 
 
 
  /**
 * 得到一个htable,注意程序用完之后要putTable在放回去,要不然又出现自由体的table连接了
 */
 public HTableInterface getTable(byte [] tableName) {
 return getTable(Bytes.toString(tableName));
 }
 
 /**
 * 得到一个htable具体方法,注意返回的为HTableInterface,强制转为htable 就ok
 * 实际是就是从LinkedList进行htable的先进先出操作
 */
 public HTableInterface getTable(String tableName) {
 LinkedList<HTableInterface> queue = tables.get(tableName);//看看队列里有没有这个tablename的queue
 if(queue == null) {
  //如果不存在则新创建一个
 queue = new LinkedList<HTableInterface>();
 tables.putIfAbsent(tableName, queue);
 return createHTable(tableName);
 }
 HTableInterface table;
 synchronized(queue) {
 table = queue.poll();
 }
 if(table == null) {
 return createHTable(tableName);
 }
 return table;
 }
 
 
 /**
 * 往queue里再增加一个table对象
 */
 public void putTable(HTableInterface table) {
 LinkedList<HTableInterface> queue = tables.get(Bytes.toString(table.getTableName()));
 synchronized(queue) {
 if(queue.size() >= maxSize) return;
 queue.add(table);
 }
 }
 protected HTableInterface createHTable(String tableName) {
 return this.tableFactory.createHTableInterface(config, Bytes.toBytes(tableName));
 }
 
 
  /**
 * 关闭tableName表的池
 */
 public void closeTablePool(final byte[] tableName) {
    closeTablePool(Bytes.toString(tableName));
 }
 /**
 * 关闭池的具体操作了,实际就是remove了
 */
 public void closeTablePool(final String tableName) {
 Queue<HTableInterface> queue = tables.get(tableName);
 synchronized (queue) {
 HTableInterface table = queue.poll();
 while (table != null) {
 this.tableFactory.releaseHTableInterface(table);
 table = queue.poll();
 }
 }
 HConnectionManager.deleteConnection(this.config, true);
 }
 
 int getCurrentPoolSize(String tableName) {
 Queue<HTableInterface> queue = tables.get(tableName);
 synchronized(queue) {
 return queue.size();
 }
 }
 }

你可能感兴趣的:(String,table,null,Class,byte)