refactoring done. Add locking.