Fix possible deadlocks
Refactor