hbase之htable线程安全性 HTablePool

 

在单线程环境下使用hbase的htable是没有问题,但是突然高并发多线程情况下就出现问题了,然后细看htable的api说明

 

Java代码 
* This class is not thread safe for updates; the underlying write buffer can 
 * be corrupted if multiple threads contend over a single HTable instance.  


 好吧 ,还是使用前没有细看api的文档说明,而且测试也没有测试多线程使用的情况,检讨下,那么对应的解决方案呢?

 

当然hbase肯定有自己的解决方案,那就是HTablePool,我们这下仔细看看api文档说明

 

Java代码   收藏代码
  1. /** 
  2.  * A simple pool of HTable instances.<p> 
  3.  * 
  4.  * Each HTablePool acts as a pool for all tables.  To use, instantiate an 
  5.  * HTablePool and use {@link #getTable(String)} to get an HTable from the pool. 
  6.  * Once you are done with it, return it to the pool with {@link #putTable(HTableInterface)}. 
  7.  *  
  8.  * <p>A pool can be created with a <i>maxSize</i> which defines the most HTable 
  9.  * references that will ever be retained for each table.  Otherwise the default 
  10.  * is {@link Integer#MAX_VALUE}. 
  11.  * 
  12.  * <p>Pool will manage its own cluster to the cluster. See {@link HConnectionManager}. 
  13.  */  
 

文档里说,使用getTable来取,当使用完了要用putTable归还,ok,这就是要使用finally块了。

 

大概的代码结构如下:

 

    /** 
     * A simple pool of HTable instances.<p> 
     * 
     * Each HTablePool acts as a pool for all tables.  To use, instantiate an 
     * HTablePool and use {@link #getTable(String)} to get an HTable from the pool. 
     * Once you are done with it, return it to the pool with {@link #putTable(HTableInterface)}. 
     *  
     * <p>A pool can be created with a <i>maxSize</i> which defines the most HTable 
     * references that will ever be retained for each table.  Otherwise the default 
     * is {@link Integer#MAX_VALUE}. 
     * 
     * <p>Pool will manage its own cluster to the cluster. See {@link HConnectionManager}. 
     */  

 

Java代码 
Result result = null;  
HTable table = null;  
try {  
    table =  (HTable)hbaseTablePool.getTable(tablename);  
    if(table == null) throw new RuntimeException(TABLE_NOT_EXIST);  
    result = table.get(xxxxxx);  
} catch (IOException e) {  
    throw new RuntimeException(e);  
}finally {  
    if(table != null) {  
        hbaseTablePool.putTable((HTableInterface)htable);  
    }  
}


 

   那pool是如何实例化的呢

Java代码

 
HTablePool  hbaseTablePool = new HTablePool(hbaseStoreFactory.getConfiguration(),this.maxConnection);  
  
//为了检验table的正确性,调用一次      
hbaseTablePool.putTable(this.hbaseTablePool.getTable(tablename));    

   仔细看看HTablePool的实现,其实不是pool的概念,只是一个计数器实现而已,相比java的线程池的实现真是很丑陋,希望hbase能给一个比较好的实现了。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值