Fix thread safety issues