Fixed memory leak problem when thread terminates at an early stage