From 2ac5ac019f67d671f09182df7da61eafec1565e6 Mon Sep 17 00:00:00 2001 From: Artem Bilan Date: Thu, 10 Nov 2016 10:34:57 -0500 Subject: [PATCH] INT-4167: Fix `ZkLockRegistryTests` race condition JIRA: https://jira.spring.io/browse/INT-4167 Since the current `ZkLock.tryLock()` is based on the fact of waiting for **at most 1 second**, that still has some timing issue for test-case, when the network delay may affect our expectation. * Add `Thread.sleep()` with `while()` to the `ZkLockRegistryTests.testTryLock()` test to spin until successful `tryLock()` **Cherry-pick to 4.3.x & 4.2.x** Note: to avoid cherry-pick conflict for `4.2.x` just fully copy/paste the modified test Conflicts: spring-integration-zookeeper/src/test/java/org/springframework/integration/zookeeper/lock/ZkLockRegistryTests.java Resolved. --- .../zookeeper/lock/ZkLockRegistryTests.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/spring-integration-zookeeper/src/test/java/org/springframework/integration/zookeeper/lock/ZkLockRegistryTests.java b/spring-integration-zookeeper/src/test/java/org/springframework/integration/zookeeper/lock/ZkLockRegistryTests.java index e5443f20e4..3cc9f19260 100644 --- a/spring-integration-zookeeper/src/test/java/org/springframework/integration/zookeeper/lock/ZkLockRegistryTests.java +++ b/spring-integration-zookeeper/src/test/java/org/springframework/integration/zookeeper/lock/ZkLockRegistryTests.java @@ -18,6 +18,7 @@ package org.springframework.integration.zookeeper.lock; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -332,7 +333,7 @@ public class ZkLockRegistryTests extends ZookeeperTestSupport { Lock lock2 = registry.obtain("bar"); assertFalse("Should not have been able to lock with zookeeper server stopped!", - lock2.tryLock(1, TimeUnit.SECONDS)); + lock2.tryLock(1, TimeUnit.SECONDS)); testingServer.restart(); @@ -355,13 +356,17 @@ public class ZkLockRegistryTests extends ZookeeperTestSupport { @Test public void testTryLock() throws Exception { ZookeeperLockRegistry registry = new ZookeeperLockRegistry(this.client); - Lock lock = registry.obtain("foo"); + for (int i = 0; i < 10; i++) { + Lock lock = registry.obtain("foo"); - assertTrue(lock.tryLock()); - lock.unlock(); + int n = 0; + while (!lock.tryLock() && n++ < 100) { + Thread.sleep(100); + } + assertThat(n, lessThan(100)); - assertTrue(lock.tryLock()); - lock.unlock(); + lock.unlock(); + } registry.destroy(); }