hbase之htable线程安全性

本文探讨了HBase中HTable在多线程环境下的并发问题,并提出了HTablePool作为解决方案。通过使用HTablePool,可以有效地管理HTable实例,避免并发更新时底层写缓冲区被破坏的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

Java代码     收藏代码
  1. * This  class  is not thread safe  for  updates; the underlying write buffer can  
  2.  * 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块了。

 

大概的代码结构如下:

 

 

Java代码     收藏代码
  1.               Result result =  null ;  
  2. HTable table = null ;  
  3. try  {  
  4.     table =  (HTable)hbaseTablePool.getTable(tablename);  
  5.     if (table ==  null throw   new  RuntimeException(TABLE_NOT_EXIST);  
  6.     result = table.get(xxxxxx);  
  7. catch  (IOException e) {  
  8.     throw   new  RuntimeException(e);  
  9. }finally  {  
  10.     if (table !=  null ) {  
  11.         hbaseTablePool.putTable((HTableInterface)htable);  
  12.     }  
  13. }  

 

   那pool是如何实例化的呢

Java代码     收藏代码
  1. HTablePool  hbaseTablePool =  new  HTablePool(hbaseStoreFactory.getConfiguration(), this .maxConnection);  
  2.   
  3. //为了检验table的正确性,调用一次       
  4. hbaseTablePool.putTable(this .hbaseTablePool.getTable(tablename));     

 

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

更多信息请查看 java进阶网 http://www.javady.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值