Improved thead safetey and fixed a dealloc bug