Replace Thread#sleep() with CountDownLatch Original patch by Davide Cavestro, with some modifications by myself