public synchronized Connection getDatabaseConnection(boolean needWritable) throws SQLException {

    DbEndpoint bestEndpoint = sortedDbEndpoints.get(0);
    if (needWritable && !bestEndpoint.isWriteable()) {
      // Can never be satisfied
      throw noWritableEndpointException;
    }

    // Close active connection if no longer valid
    if (activeConnection != null && !activeConnection.isValid(5)) {
      closeActiveConnection();
    }

    // If the active connection is good and it's the best endpoint, keep it.
    if (activeConnection != null && !isBetterEndpoint(bestEndpoint, connectedEndpoint)) {
      return activeConnection;
    }
    // See if we can do better
    Pair<DbEndpoint, Connection> endpointConnectionPair = connectToBestAvailableEndpoint(needWritable);
    if (connectedEndpoint == endpointConnectionPair.getFirst()) {
      // No better endpoint was available.
      logger.debug("Still connected to {}", connectedEndpoint.getUrl());
    } else {
      // New connection established
      closeActiveConnection();
      connectedEndpoint = endpointConnectionPair.getFirst();
      activeConnection = endpointConnectionPair.getSecond();
      String qualifier = connectedEndpoint.isWriteable() ? "writable" : "read-only";
      logger.info("Connected to {} endpoint: {}", qualifier, connectedEndpoint.getUrl());
    }
    return activeConnection;
  }
@return a JDBC {@link Connection} to the database.  An existing connection will be reused,
unless a connection to a better-ranked enpoint is available.
@param needWritable whether the database instance needs to be writeable.
@throws SQLException
ambry-mysql/src/main/java/com/github/ambry/mysql/MySqlDataAccessor.java