@Override
        @SuppressWarnings("unchecked")
        public void run() {
            DBPort connection = null;
            try {
                ServerDescription currentServerDescription = getConnectingServerDescription(null);
                Throwable currentException = null;
                while (!isClosed) {
                    ServerDescription previousServerDescription = currentServerDescription;
                    Throwable previousException = currentException;
                    try {
                        if (connection == null) {
                            connection = new DBPort(serverAddress, null, getOptions(), 0);
                        }
                        try {
                            currentServerDescription = lookupServerDescription(connection);
                        } catch (IOException e) {
                            // in case the connection has been reset since the last run, do one retry immediately before reporting that the
                            // server is down
                            count = 0;
                            elapsedNanosSum = 0;
                            if (connection != null) {
                                connection.close();
                                connection = null;
                                connectionProvider.invalidate();
                            }
                            connection = new DBPort(serverAddress, null, getOptions(), 0);
                            try {
                                currentServerDescription = lookupServerDescription(connection);
                            } catch (IOException e1) {
                                connection.close();
                                connection = null;
                                throw e1;
                            }
                        }
                    } catch (Throwable t) {
                        currentException = t;
                        currentServerDescription = getConnectingServerDescription(t);
                    }

                    if (!isClosed) {
                        try {
                            logStateChange(previousServerDescription, previousException, currentServerDescription, currentException);
                            sendStateChangedEvent(previousServerDescription, currentServerDescription);
                        } catch (Throwable t) {
                            LOGGER.log(Level.WARNING, "Exception in monitor thread during notification of server state change", t);
                        }
                    }
                    waitForNext();
                }
            } finally {
                if (connection != null) {
                    connection.close();
                }
            }
        }