Index: src/java/org/apache/hadoop/hbase/client/HTablePool.java =================================================================== --- src/java/org/apache/hadoop/hbase/client/HTablePool.java (revision 0) +++ src/java/org/apache/hadoop/hbase/client/HTablePool.java (revision 0) @@ -0,0 +1,94 @@ +/** + * Copyright 2009 The Apache Software Foundation + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.hbase.client; + +import java.io.IOException; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.hadoop.hbase.util.Bytes; + +class HTablePoolEntry { + public HTable table; + public volatile int references; + public HTablePoolEntry(HTable table) { + this.table = table; + references = 0; + } +} + +public class HTablePool { + private static final Log LOG = LogFactory.getLog(HTablePool.class); + private static Map tableMap = + new TreeMap(Bytes.BYTES_COMPARATOR); + + /** + * Get a pooled HTable reference + * @param tableName the table name + * @return a HTable instance + * @throws IOException + */ + public static HTable getTable(byte[] tableName) throws IOException { + synchronized (tableMap) { + HTablePoolEntry entry = tableMap.get(tableName); + if (entry == null) { + HTable table = new HTable(tableName); + entry = new HTablePoolEntry(table); + tableMap.put(tableName, entry); + } + entry.references++; + return entry.table; + } + } + + /** + * Get a pooled HTable reference + * @param tableName the table name + * @return a HTable instance + * @throws IOException + */ + public static HTable getTable(String tableName) throws IOException { + return getTable(Bytes.toBytes(tableName)); + } + + /** + * Release a HTable reference + * @param table the table instance + */ + public static void putTable(HTable table) { + synchronized (tableMap) { + byte[] tableName = table.getTableName(); + HTablePoolEntry entry = tableMap.get(tableName); + if (entry != null) { + if (--entry.references <= 0) { + if (entry.references < 0) { + LOG.warn("reference count for pooled HTable entry for '" + + Bytes.toString(tableName) + "' went negative"); + } + tableMap.remove(tableName); + } + } + } + } +}