Added some thread safeness code and tests