Fix resource cleanup

@tianx2 please take a look