This commit fices the threading problem and some memry leak.