fix a deadlock bug along with unit tests