Some thread-safety changes and tests