added memory leak detection thread safety

clean up and and rebased from #418