thread-safety; some refactoring