HTable close的时候,会先flushCommits,将writerBuffer中的List<Put>一次性通过connection的processBatch方法处理掉,然后进入close connection逻辑,依据也是reference count,先对其减1,当为0或者是过期connection,就会执行close connection并从HBASE_INSTANCES中remove掉。
关闭步骤:
1. 关闭HMasterInterface
2. 关闭一串HRegionInterface
3. 关闭zookeeper watcher
HConnectionImplementation connection = HBASE_INSTANCES
.get(connectionKey);
if (connection != null) {
connection.decCount();
if (connection.isZeroReference() || staleConnection) {
HBASE_INSTANCES.remove(connectionKey);
connection.close(stopProxy);
} else if (stopProxy) {
connection.stopProxyOnClose(stopProxy);
}
}else {
LOG.error("Connection not found in the list, can't delete it "+
"(connection key="+connectionKey+"). May be the key was modified?");
}
HBaseAdmin内部也是一样,也是reference了一个HConnection,可以认为和HTable是共享HConnection
分析到这里再联想到之前的报错信息"java.io.IOException: org.apache.Hadoop.hbase.client.HConnectionManager$HConnectionImplementation@b7c96a9 closed",应该是client reference count数的问题,果然在我的HBaseClient代码里面在初始化环节会new一个singleton HBaseClient,里面new一个HBaseAdmin(thread共享),在各个thread启动时候会new 一个threadloca的htable对象
private HTable getHTable() throws IOException {
HTable htable = threadLocalHtable.get();
if (htable == null) {
htable = new HTable(conf, tableName);
htable.setAutoFlush(autoFlush);
htable.setWriteBufferSize(writeBufferSize);
threadLocalHtable.set(htable);
}
return htable;
}
但是我的close方法写的有问题,把HBaseAdmin close了很多遍(每个thread close了一次)
public synchronized void close() throws IOException {
HTable table = threadLocalHtable.get();
if (table != null) {
table.close();
table = null;
threadLocalHtable.remove();
}
if (admin != null) {
admin.close();
}
}
假设一种场景,有10个writer线程,那么reference count是11 (10个HTable和1个HBaseAdmin),前5个thread close没问题,第6个thread先close htable,然后发现引用数为0了,它关闭了HConnection,然后再close admin无效,但是其余4个线程这时候有可能在执行flush操作,HConnection既然已经断了,那肯定没办法flush完啊,抛出异常出来
public void flush() throws IOException {
if (getPutBuffer().size() > 0) {
getHTable().put(getPutBuffer());
clearPutBuffer();
}
}
知道了错误原因后,果断在close HBaseAdmin后,把它指向NULL,这样就不会导致重复关闭的问题了
if (admin != null) {
admin.close();
admin = null;
}
这个问题困扰我几天,网上又找不到任何资料,后来还是看了HBase源代码才有新的发现并解决的,看来真碰到问题一定要懂底层代码才行。
更多Hadoop相关信息见Hadoop 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=13
