Added locking functionality for race prevention