Added a thread-safe implementation of the previous code