Modified to implement thread-safety efficiently