You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@calcite.apache.org by jh...@apache.org on 2015/03/28 22:23:56 UTC

[07/10] incubator-calcite git commit: [CALCITE-640] Avatica server should expire stale connections/statements (Nick Dimiduk)

[CALCITE-640] Avatica server should expire stale connections/statements (Nick Dimiduk)

Close apache/incubator-calcite#65


Project: http://git-wip-us.apache.org/repos/asf/incubator-calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-calcite/commit/0f824f81
Tree: http://git-wip-us.apache.org/repos/asf/incubator-calcite/tree/0f824f81
Diff: http://git-wip-us.apache.org/repos/asf/incubator-calcite/diff/0f824f81

Branch: refs/heads/master
Commit: 0f824f819234c5d08aac88f73ba50894b8b23a54
Parents: c446e02
Author: Nick Dimiduk <nd...@gmail.com>
Authored: Tue Mar 24 15:25:00 2015 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Fri Mar 27 20:01:27 2015 -0700

----------------------------------------------------------------------
 .../org/apache/calcite/avatica/server/Main.java |  14 +-
 avatica/pom.xml                                 |   4 +
 .../apache/calcite/avatica/jdbc/JdbcMeta.java   | 198 ++++++++++++++++---
 .../calcite/avatica/remote/JsonService.java     |   2 -
 .../calcite/avatica/remote/LocalService.java    |   7 +-
 .../calcite/avatica/remote/RemoteMeta.java      |   4 +-
 .../calcite/avatica/test/RemoteDriverTest.java  |  39 ++--
 7 files changed, 217 insertions(+), 51 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica-server/src/main/java/org/apache/calcite/avatica/server/Main.java
----------------------------------------------------------------------
diff --git a/avatica-server/src/main/java/org/apache/calcite/avatica/server/Main.java b/avatica-server/src/main/java/org/apache/calcite/avatica/server/Main.java
index d3a24f0..f8416d6 100644
--- a/avatica-server/src/main/java/org/apache/calcite/avatica/server/Main.java
+++ b/avatica-server/src/main/java/org/apache/calcite/avatica/server/Main.java
@@ -36,10 +36,16 @@ public class Main {
   }
 
   /**
-   * Create and start an {@link HttpServer}.
-   * @param args <br />&nbsp;&nbsp;args[0]: the {@link Meta.Factory} class name.<br />
-   *             &nbsp;&nbsp;args[1:]: arguments passed along to
-   *             {@link Meta.Factory#create(java.util.List)}
+   * Creates and starts an {@link HttpServer}.
+   *
+   * <p>Arguments are as follows:
+   * <ul>
+   *   <li>args[0]: the {@link Meta.Factory} class name
+   *   <li>args[1+]: arguments passed along to
+   *   {@link Meta.Factory#create(java.util.List)}
+   * </ul>
+   *
+   * @param args Command-line arguments
    */
   public static HttpServer start(String[] args)
       throws ClassNotFoundException, InstantiationException,

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/pom.xml
----------------------------------------------------------------------
diff --git a/avatica/pom.xml b/avatica/pom.xml
index 0e58323..0bacc4a 100644
--- a/avatica/pom.xml
+++ b/avatica/pom.xml
@@ -41,6 +41,10 @@ limitations under the License.
       <artifactId>jackson-databind</artifactId>
     </dependency>
     <dependency>
+      <groupId>com.google.guava</groupId>
+      <artifactId>guava</artifactId>
+    </dependency>
+    <dependency>
       <groupId>commons-logging</groupId>
       <artifactId>commons-logging</artifactId>
     </dependency>

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/src/main/java/org/apache/calcite/avatica/jdbc/JdbcMeta.java
----------------------------------------------------------------------
diff --git a/avatica/src/main/java/org/apache/calcite/avatica/jdbc/JdbcMeta.java b/avatica/src/main/java/org/apache/calcite/avatica/jdbc/JdbcMeta.java
index 24bdbda..627a0d7 100644
--- a/avatica/src/main/java/org/apache/calcite/avatica/jdbc/JdbcMeta.java
+++ b/avatica/src/main/java/org/apache/calcite/avatica/jdbc/JdbcMeta.java
@@ -23,6 +23,11 @@ import org.apache.calcite.avatica.Meta;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
+
 import java.lang.reflect.Array;
 import java.lang.reflect.Type;
 import java.math.BigDecimal;
@@ -43,6 +48,7 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 /** Implementation of {@link Meta} upon an existing JDBC data source. */
 public class JdbcMeta implements Meta {
@@ -81,14 +87,64 @@ public class JdbcMeta implements Meta {
     SQL_TYPE_TO_JAVA_TYPE.put(Types.ARRAY, Array.class);
   }
 
+  //
+  // Constants for connection cache settings.
+  //
+
+  private static final String CONN_CACHE_KEY_BASE = "avatica.connectioncache";
+  /** JDBC connection property for setting connection cache concurrency level. */
+  public static final String CONN_CACHE_CONCURRENCY_KEY =
+      CONN_CACHE_KEY_BASE + ".concurrency";
+  public static final String DEFAULT_CONN_CACHE_CONCURRENCY_LEVEL = "10";
+  /** JDBC connection property for setting connection cache initial capacity. */
+  public static final String CONN_CACHE_INITIAL_CAPACITY_KEY =
+      CONN_CACHE_KEY_BASE + ".initialcapacity";
+  public static final String DEFAULT_CONN_CACHE_INITIAL_CAPACITY = "100";
+  /** JDBC connection property for setting connection cache maximum capacity. */
+  public static final String CONN_CACHE_MAX_CAPACITY_KEY =
+      CONN_CACHE_KEY_BASE + ".maxcapacity";
+  public static final String DEFAULT_CONN_CACHE_MAX_CAPACITY = "1000";
+  /** JDBC connection property for setting connection cache expiration duration. */
+  public static final String CONN_CACHE_EXPIRY_DURATION_KEY =
+      CONN_CACHE_KEY_BASE + ".expirydiration";
+  public static final String DEFAULT_CONN_CACHE_EXPIRY_DURATION = "10";
+  /** JDBC connection property for setting connection cache expiration unit. */
+  public static final String CONN_CACHE_EXPIRY_UNIT_KEY = CONN_CACHE_KEY_BASE + ".expiryunit";
+  public static final String DEFAULT_CONN_CACHE_EXPIRY_UNIT = TimeUnit.MINUTES.name();
+
+  //
+  // Constants for statement cache settings.
+  //
+
+  private static final String STMT_CACHE_KEY_BASE = "avatica.statementcache";
+  /** JDBC connection property for setting connection cache concurrency level. */
+  public static final String STMT_CACHE_CONCURRENCY_KEY =
+      STMT_CACHE_KEY_BASE + ".concurrency";
+  public static final String DEFAULT_STMT_CACHE_CONCURRENCY_LEVEL = "100";
+  /** JDBC connection property for setting connection cache initial capacity. */
+  public static final String STMT_CACHE_INITIAL_CAPACITY_KEY =
+      STMT_CACHE_KEY_BASE + ".initialcapacity";
+  public static final String DEFAULT_STMT_CACHE_INITIAL_CAPACITY = "1000";
+  /** JDBC connection property for setting connection cache maximum capacity. */
+  public static final String STMT_CACHE_MAX_CAPACITY_KEY =
+      STMT_CACHE_KEY_BASE + ".maxcapacity";
+  public static final String DEFAULT_STMT_CACHE_MAX_CAPACITY = "10000";
+  /** JDBC connection property for setting connection cache expiration duration. */
+  public static final String STMT_CACHE_EXPIRY_DURATION_KEY =
+      STMT_CACHE_KEY_BASE + ".expirydiration";
+  public static final String DEFAULT_STMT_CACHE_EXPIRY_DURATION = "5";
+  /** JDBC connection property for setting connection cache expiration unit. */
+  public static final String STMT_CACHE_EXPIRY_UNIT_KEY = STMT_CACHE_KEY_BASE + ".expiryunit";
+  public static final String DEFAULT_STMT_CACHE_EXPIRY_UNIT = TimeUnit.MINUTES.name();
+
   private static final String DEFAULT_CONN_ID =
       UUID.fromString("00000000-0000-0000-0000-000000000000").toString();
 
   private final String url;
   private final Properties info;
   private final Connection connection; // TODO: remove default connection
-  private final Map<String, Connection> connectionMap = new HashMap<>();
-  private final Map<Integer, StatementInfo> statementMap = new HashMap<>();
+  private final Cache<String, Connection> connectionCache;
+  private final Cache<Integer, StatementInfo> statementCache;
 
   /**
    * Convert from JDBC metadata to Avatica columns.
@@ -148,6 +204,58 @@ public class JdbcMeta implements Meta {
     return signature(metaData, null, null);
   }
 
+  /** Callback for {@link #connectionCache} member expiration. */
+  private class ConnectionExpiryHandler
+      implements RemovalListener<String, Connection> {
+
+    public void onRemoval(RemovalNotification<String, Connection> notification) {
+      String connectionId = notification.getKey();
+      Connection doomed = notification.getValue();
+      // is String.equals() more efficient?
+      if (notification.getValue() == connection) {
+        return;
+      }
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Expiring connection " + connectionId + " because "
+            + notification.getCause());
+      }
+      try {
+        if (doomed != null) {
+          doomed.close();
+        }
+      } catch (Throwable t) {
+        LOG.info("Exception thrown while expiring connection " + connectionId, t);
+      }
+    }
+  }
+
+  /** Callback for {@link #statementCache} member expiration. */
+  private class StatementExpiryHandler
+      implements RemovalListener<Integer, StatementInfo> {
+    public void onRemoval(RemovalNotification<Integer, StatementInfo> notification) {
+      Integer stmtId = notification.getKey();
+      StatementInfo doomed = notification.getValue();
+      if (doomed == null) {
+        // log/throw?
+        return;
+      }
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Expiring statement " + stmtId + " because "
+            + notification.getCause());
+      }
+      try {
+        if (doomed.resultSet != null) {
+          doomed.resultSet.close();
+        }
+        if (doomed.statement != null) {
+          doomed.statement.close();
+        }
+      } catch (Throwable t) {
+        LOG.info("Exception thrown while expiring statement " + stmtId);
+      }
+    }
+  }
+
   /**
    * @param url a database url of the form
    *  <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
@@ -184,7 +292,48 @@ public class JdbcMeta implements Meta {
     this.url = url;
     this.info = info;
     this.connection = DriverManager.getConnection(url, info);
-    this.connectionMap.put(DEFAULT_CONN_ID, connection);
+
+    int concurrencyLevel = Integer.parseInt(
+        info.getProperty(CONN_CACHE_CONCURRENCY_KEY, DEFAULT_CONN_CACHE_CONCURRENCY_LEVEL));
+    int initialCapacity = Integer.parseInt(
+        info.getProperty(CONN_CACHE_INITIAL_CAPACITY_KEY, DEFAULT_CONN_CACHE_INITIAL_CAPACITY));
+    long maxCapacity = Long.parseLong(
+        info.getProperty(CONN_CACHE_MAX_CAPACITY_KEY, DEFAULT_CONN_CACHE_MAX_CAPACITY));
+    long connectionExpiryDuration = Long.parseLong(
+        info.getProperty(CONN_CACHE_EXPIRY_DURATION_KEY, DEFAULT_CONN_CACHE_EXPIRY_DURATION));
+    TimeUnit connectionExpiryUnit = TimeUnit.valueOf(
+        info.getProperty(CONN_CACHE_EXPIRY_UNIT_KEY, DEFAULT_CONN_CACHE_EXPIRY_UNIT));
+    this.connectionCache = CacheBuilder.newBuilder()
+        .concurrencyLevel(concurrencyLevel)
+        .initialCapacity(initialCapacity)
+        .maximumSize(maxCapacity)
+        .expireAfterAccess(connectionExpiryDuration, connectionExpiryUnit)
+        .removalListener(new ConnectionExpiryHandler())
+        .build();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("instantiated connection cache: " + connectionCache.stats());
+    }
+
+    concurrencyLevel = Integer.parseInt(
+        info.getProperty(STMT_CACHE_CONCURRENCY_KEY, DEFAULT_STMT_CACHE_CONCURRENCY_LEVEL));
+    initialCapacity = Integer.parseInt(
+        info.getProperty(STMT_CACHE_INITIAL_CAPACITY_KEY, DEFAULT_STMT_CACHE_INITIAL_CAPACITY));
+    maxCapacity = Long.parseLong(
+        info.getProperty(STMT_CACHE_MAX_CAPACITY_KEY, DEFAULT_STMT_CACHE_MAX_CAPACITY));
+    connectionExpiryDuration = Long.parseLong(
+        info.getProperty(STMT_CACHE_EXPIRY_DURATION_KEY, DEFAULT_STMT_CACHE_EXPIRY_DURATION));
+    connectionExpiryUnit = TimeUnit.valueOf(
+        info.getProperty(STMT_CACHE_EXPIRY_UNIT_KEY, DEFAULT_STMT_CACHE_EXPIRY_UNIT));
+    this.statementCache = CacheBuilder.newBuilder()
+        .concurrencyLevel(concurrencyLevel)
+        .initialCapacity(initialCapacity)
+        .maximumSize(maxCapacity)
+        .expireAfterAccess(connectionExpiryDuration, connectionExpiryUnit)
+        .removalListener(new StatementExpiryHandler())
+        .build();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("instantiated statement cache: " + statementCache.stats());
+    }
   }
 
   public String getSqlKeywords() {
@@ -411,10 +560,12 @@ public class JdbcMeta implements Meta {
   }
 
   protected Connection getConnection(String id) throws SQLException {
-    if (connectionMap.get(id) == null) {
-      connectionMap.put(id, DriverManager.getConnection(url, info));
+    Connection conn = connectionCache.getIfPresent(id);
+    if (conn == null) {
+      conn = DriverManager.getConnection(url, info);
+      connectionCache.put(id, conn);
     }
-    return connectionMap.get(id);
+    return conn;
   }
 
   public StatementHandle createStatement(ConnectionHandle ch) {
@@ -422,7 +573,7 @@ public class JdbcMeta implements Meta {
       final Connection conn = getConnection(ch.id);
       final Statement statement = conn.createStatement();
       final int id = System.identityHashCode(statement);
-      statementMap.put(id, new StatementInfo(statement));
+      statementCache.put(id, new StatementInfo(statement));
       StatementHandle h = new StatementHandle(ch.id, id, null);
       if (LOG.isTraceEnabled()) {
         LOG.trace("created statement " + h);
@@ -434,8 +585,8 @@ public class JdbcMeta implements Meta {
   }
 
   @Override public void closeStatement(StatementHandle h) {
-    Statement stmt = statementMap.get(h.id).statement;
-    if (stmt == null) {
+    StatementInfo info = statementCache.getIfPresent(h.id);
+    if (info == null || info.statement == null) {
       LOG.debug("client requested close unknown statement " + h);
       return;
     }
@@ -443,19 +594,19 @@ public class JdbcMeta implements Meta {
       LOG.trace("closing statement " + h);
     }
     try {
-      boolean isOwned =
-          stmt.getConnection() == connectionMap.get(h.connectionId);
-      stmt.close();
-      assert isOwned : "no connection found while closing " + h;
+      if (info.resultSet != null) {
+        info.resultSet.close();
+      }
+      info.statement.close();
     } catch (SQLException e) {
       throw propagate(e);
     } finally {
-      statementMap.remove(h.id);
+      statementCache.invalidate(h.id);
     }
   }
 
   @Override public void closeConnection(ConnectionHandle ch) {
-    Connection conn = connectionMap.get(ch.id);
+    Connection conn = connectionCache.getIfPresent(ch.id);
     if (conn == null) {
       LOG.debug("client requested close unknown connection " + ch);
       return;
@@ -468,7 +619,7 @@ public class JdbcMeta implements Meta {
     } catch (SQLException e) {
       throw propagate(e);
     } finally {
-      connectionMap.remove(ch.id);
+      connectionCache.invalidate(ch.id);
     }
   }
 
@@ -488,9 +639,10 @@ public class JdbcMeta implements Meta {
       final Connection conn = getConnection(ch.id);
       final PreparedStatement statement = conn.prepareStatement(sql);
       final int id = System.identityHashCode(statement);
-      statementMap.put(id, new StatementInfo(statement));
-      StatementHandle h = new StatementHandle(ch.id, id, signature(
-          statement.getMetaData(), statement.getParameterMetaData(), sql));
+      statementCache.put(id, new StatementInfo(statement));
+      StatementHandle h = new StatementHandle(ch.id, id,
+          signature(statement.getMetaData(), statement.getParameterMetaData(),
+              sql));
       if (LOG.isTraceEnabled()) {
         LOG.trace("prepared statement " + h);
       }
@@ -507,7 +659,7 @@ public class JdbcMeta implements Meta {
       final PreparedStatement statement = connection.prepareStatement(sql);
       final int id = System.identityHashCode(statement);
       final StatementInfo info = new StatementInfo(statement);
-      statementMap.put(id, info);
+      statementCache.put(id, info);
       info.resultSet = statement.executeQuery();
       MetaResultSet mrs = JdbcResultSet.create(ch.id, id, info.resultSet);
       if (LOG.isTraceEnabled()) {
@@ -525,10 +677,10 @@ public class JdbcMeta implements Meta {
     if (LOG.isTraceEnabled()) {
       LOG.trace("fetching " + h + " offset:" + offset + " fetchMaxRowCount:" + fetchMaxRowCount);
     }
-    final StatementInfo statementInfo = statementMap.get(h.id);
     try {
-      assert statementInfo.statement.getConnection()
-          == connectionMap.get(h.connectionId);
+      final StatementInfo statementInfo = Objects.requireNonNull(
+          statementCache.getIfPresent(h.id),
+          "Statement not found, potentially expired. " + h);
       if (statementInfo.resultSet == null || parameterValues != null) {
         if (statementInfo.resultSet != null) {
           statementInfo.resultSet.close();

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/src/main/java/org/apache/calcite/avatica/remote/JsonService.java
----------------------------------------------------------------------
diff --git a/avatica/src/main/java/org/apache/calcite/avatica/remote/JsonService.java b/avatica/src/main/java/org/apache/calcite/avatica/remote/JsonService.java
index dc4268b..b8d640d 100644
--- a/avatica/src/main/java/org/apache/calcite/avatica/remote/JsonService.java
+++ b/avatica/src/main/java/org/apache/calcite/avatica/remote/JsonService.java
@@ -130,7 +130,6 @@ public abstract class JsonService implements Service {
     }
   }
 
-  @Override
   public CloseStatementResponse apply(CloseStatementRequest request) {
     try {
       return decode(apply(encode(request)), CloseStatementResponse.class);
@@ -139,7 +138,6 @@ public abstract class JsonService implements Service {
     }
   }
 
-  @Override
   public CloseConnectionResponse apply(CloseConnectionRequest request) {
     try {
       return decode(apply(encode(request)), CloseConnectionResponse.class);

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/src/main/java/org/apache/calcite/avatica/remote/LocalService.java
----------------------------------------------------------------------
diff --git a/avatica/src/main/java/org/apache/calcite/avatica/remote/LocalService.java b/avatica/src/main/java/org/apache/calcite/avatica/remote/LocalService.java
index 719ef1d..842ebd6 100644
--- a/avatica/src/main/java/org/apache/calcite/avatica/remote/LocalService.java
+++ b/avatica/src/main/java/org/apache/calcite/avatica/remote/LocalService.java
@@ -190,14 +190,13 @@ public class LocalService implements Service {
     return new CreateStatementResponse(h.connectionId, h.id);
   }
 
-  @Override
   public CloseStatementResponse apply(CloseStatementRequest request) {
-    meta.closeStatement(new Meta.StatementHandle(
-        request.connectionId, request.statementId, null));
+    meta.closeStatement(
+        new Meta.StatementHandle(request.connectionId, request.statementId,
+            null));
     return new CloseStatementResponse();
   }
 
-  @Override
   public CloseConnectionResponse apply(CloseConnectionRequest request) {
     meta.closeConnection(new Meta.ConnectionHandle(request.connectionId));
     return new CloseConnectionResponse();

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/src/main/java/org/apache/calcite/avatica/remote/RemoteMeta.java
----------------------------------------------------------------------
diff --git a/avatica/src/main/java/org/apache/calcite/avatica/remote/RemoteMeta.java b/avatica/src/main/java/org/apache/calcite/avatica/remote/RemoteMeta.java
index e72ad8b..772321c 100644
--- a/avatica/src/main/java/org/apache/calcite/avatica/remote/RemoteMeta.java
+++ b/avatica/src/main/java/org/apache/calcite/avatica/remote/RemoteMeta.java
@@ -118,8 +118,8 @@ class RemoteMeta extends MetaImpl {
     try {
       synchronized (callback.getMonitor()) {
         callback.clear();
-        response = service.apply(new Service.PrepareAndExecuteRequest(
-            ch.id, sql, maxRowCount));
+        response = service.apply(
+            new Service.PrepareAndExecuteRequest(ch.id, sql, maxRowCount));
         callback.assign(response.signature, response.firstFrame);
       }
       callback.execute();

http://git-wip-us.apache.org/repos/asf/incubator-calcite/blob/0f824f81/avatica/src/test/java/org/apache/calcite/avatica/test/RemoteDriverTest.java
----------------------------------------------------------------------
diff --git a/avatica/src/test/java/org/apache/calcite/avatica/test/RemoteDriverTest.java b/avatica/src/test/java/org/apache/calcite/avatica/test/RemoteDriverTest.java
index db4b42a..0f6ab8d 100644
--- a/avatica/src/test/java/org/apache/calcite/avatica/test/RemoteDriverTest.java
+++ b/avatica/src/test/java/org/apache/calcite/avatica/test/RemoteDriverTest.java
@@ -26,6 +26,8 @@ import org.apache.calcite.avatica.remote.LocalService;
 import org.apache.calcite.avatica.remote.MockJsonService;
 import org.apache.calcite.avatica.remote.Service;
 
+import com.google.common.cache.Cache;
+
 import net.hydromatic.scott.data.hsqldb.ScottHsqldb;
 
 import org.junit.Before;
@@ -200,7 +202,7 @@ public class RemoteDriverTest {
   @Test public void testStatementLifecycle() throws Exception {
     try (AvaticaConnection connection = (AvaticaConnection) ljs()) {
       Map<Integer, AvaticaStatement> clientMap = connection.statementMap;
-      Map<Integer, Statement> serverMap =
+      Cache<Integer, Object> serverMap =
           QuasiRemoteJdbcServiceFactory.getRemoteStatementMap(connection);
       assertEquals(0, clientMap.size());
       assertEquals(0, serverMap.size());
@@ -217,27 +219,29 @@ public class RemoteDriverTest {
     final String sql = "select * from (values (1, 'a'))";
     Connection conn1 = ljs();
     Connection conn2 = ljs();
-    Map<String, Connection> connectionMap =
+    Cache<String, Connection> connectionMap =
         QuasiRemoteJdbcServiceFactory.getRemoteConnectionMap(
             (AvaticaConnection) conn1);
-    assertEquals("should contain at least the default connection",
-        1, connectionMap.size());
+    assertEquals("connection cache should start empty",
+        0, connectionMap.size());
     PreparedStatement conn1stmt1 = conn1.prepareStatement(sql);
     assertEquals(
         "statement creation implicitly creates a connection server-side",
-        2, connectionMap.size());
+        1, connectionMap.size());
     PreparedStatement conn2stmt1 = conn2.prepareStatement(sql);
     assertEquals(
         "statement creation implicitly creates a connection server-side",
-        3, connectionMap.size());
+        2, connectionMap.size());
     AvaticaPreparedStatement s1 = (AvaticaPreparedStatement) conn1stmt1;
     AvaticaPreparedStatement s2 = (AvaticaPreparedStatement) conn2stmt1;
     assertFalse("connection id's should be unique",
         s1.handle.connectionId.equalsIgnoreCase(s2.handle.connectionId));
     conn2.close();
-    conn1.close();
     assertEquals("closing a connection closes the server-side connection",
         1, connectionMap.size());
+    conn1.close();
+    assertEquals("closing a connection closes the server-side connection",
+        0, connectionMap.size());
   }
 
   private void checkStatementExecuteQuery(Connection connection)
@@ -318,8 +322,9 @@ public class RemoteDriverTest {
   public static class LocalJdbcServiceFactory implements Service.Factory {
     @Override public Service create(AvaticaConnection connection) {
       try {
-        return new LocalService(new JdbcMeta(CONNECTION_SPEC.url,
-            CONNECTION_SPEC.username, CONNECTION_SPEC.password));
+        return new LocalService(
+            new JdbcMeta(CONNECTION_SPEC.url, CONNECTION_SPEC.username,
+                CONNECTION_SPEC.password));
       } catch (SQLException e) {
         throw new RuntimeException(e);
       }
@@ -355,7 +360,7 @@ public class RemoteDriverTest {
      * statement map from the other side.
      * TODO: refactor tests to replace reflection with package-local access
      */
-    static Map<Integer, Statement>
+    static Cache<Integer, Object>
     getRemoteStatementMap(AvaticaConnection connection) throws Exception {
       Field metaF = AvaticaConnection.class.getDeclaredField("meta");
       metaF.setAccessible(true);
@@ -371,9 +376,10 @@ public class RemoteDriverTest {
           remoteMetaServiceService.getClass().getDeclaredField("meta");
       remoteMetaServiceServiceMetaF.setAccessible(true);
       JdbcMeta serverMeta = (JdbcMeta) remoteMetaServiceServiceMetaF.get(remoteMetaServiceService);
-      Field jdbcMetaStatementMapF = JdbcMeta.class.getDeclaredField("statementMap");
+      Field jdbcMetaStatementMapF = JdbcMeta.class.getDeclaredField("statementCache");
       jdbcMetaStatementMapF.setAccessible(true);
-      return (Map<Integer, Statement>) jdbcMetaStatementMapF.get(serverMeta);
+      //noinspection unchecked
+      return (Cache<Integer, Object>) jdbcMetaStatementMapF.get(serverMeta);
     }
 
     /**
@@ -381,7 +387,7 @@ public class RemoteDriverTest {
      * connection map from the other side.
      * TODO: refactor tests to replace reflection with package-local access
      */
-    static Map<String, Connection>
+    static Cache<String, Connection>
     getRemoteConnectionMap(AvaticaConnection connection) throws Exception {
       Field metaF = AvaticaConnection.class.getDeclaredField("meta");
       metaF.setAccessible(true);
@@ -397,9 +403,10 @@ public class RemoteDriverTest {
           remoteMetaServiceService.getClass().getDeclaredField("meta");
       remoteMetaServiceServiceMetaF.setAccessible(true);
       JdbcMeta serverMeta = (JdbcMeta) remoteMetaServiceServiceMetaF.get(remoteMetaServiceService);
-      Field jdbcMetaStatementMapF = JdbcMeta.class.getDeclaredField("connectionMap");
-      jdbcMetaStatementMapF.setAccessible(true);
-      return (Map<String, Connection>) jdbcMetaStatementMapF.get(serverMeta);
+      Field jdbcMetaConnectionCacheF = JdbcMeta.class.getDeclaredField("connectionCache");
+      jdbcMetaConnectionCacheF.setAccessible(true);
+      //noinspection unchecked
+      return (Cache<String, Connection>) jdbcMetaConnectionCacheF.get(serverMeta);
     }
   }