Added locking to make it thread safe