first commit for new repo
[sdc/sdc-titan-cassandra.git] / src / main / java / com / thinkaurelius / titan / diskstorage / cassandra / thrift / thriftpool / CTConnectionPool.java
1 package com.thinkaurelius.titan.diskstorage.cassandra.thrift.thriftpool;
2
3 import org.apache.commons.pool.KeyedPoolableObjectFactory;
4 import org.apache.commons.pool.impl.GenericKeyedObjectPool;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7
8 /**
9  * This class extends Apache Commons Pool's GenericKeyedObjectPool, adding
10  * two methods that support Java 5 generic type safety.  However, a
11  * programmer can still cause RuntimeExceptions related to type errors
12  * by mixing calls to these additional methods with calls to the legacy
13  * "Object"-typed methods.
14  * <p/>
15  * <p/>
16  * Unfortunately, GenericKeyedObjectPool is not actually generic in the
17  * type-system sense.  All of its methods are typed to Object, forcing the
18  * client programmer to sprinkle code with casts.  This class centralizes
19  * that casting to a single method.
20  * <p/>
21  * <p/>
22  * As a corollary, this class is slightly less flexible than
23  * GenericKeyedObjectPool, as this class can only store keys and pooled
24  * objects each of a single type, whereas GenericKeyedObjectPool could
25  * theoretically contain heterogeneous types of each.  However, I do not
26  * need the flexibility of heterogeneous types for pooling Thrift
27  * connections, the original work that precipitated writing this class.
28  *
29  * @param <K> Key type
30  * @param <V> Pooled object type
31  * @author Dan LaRocque <dalaro@hopcount.org>
32  */
33 public class CTConnectionPool extends GenericKeyedObjectPool<String, CTConnection> {
34     
35     private static final Logger log =
36             LoggerFactory.getLogger(CTConnectionPool.class);
37     
38     public CTConnectionPool(KeyedPoolableObjectFactory<String, CTConnection> factory) {
39         super(factory);
40     }
41
42     /**
43      * If {@code conn} is non-null and is still open, then call
44      * {@link GenericKeyedObjectPool#returnObject(String, CTConnection),
45      * catching and logging and Exception that method might generate. 
46      * This method does not emit any exceptions.
47      * 
48      * @param keyspace The key of the pooled object being returned
49      * @param conn The pooled object being returned, or null to do nothing
50      */
51     public void returnObjectUnsafe(String keyspace, CTConnection conn) {
52         if (conn != null && conn.isOpen()) {
53             try {
54                 returnObject(keyspace, conn);
55             } catch (Exception e) {
56                 log.warn("Failed to return Cassandra connection to pool", e);
57                 log.warn(
58                         "Failure context: keyspace={}, pool={}, connection={}",
59                         new Object[] { keyspace, this, conn });
60             }
61         }
62     }
63 }
64