cleanup, fix resource starvation bug, add some thread safety