properly close connections and stop threads