Fixed a memory and a threading issue