RetriableLock implements Lock { @Override public String acquire(final List<String> keys, final String storeId, final long expiration) { return retryTemplate.execute(ctx -> { final String token = lock.acquire(keys, storeId, expiration); if (StringUtils.isEmpty(token)) { throw new LockNotAvailableException(String.format("Lock not available for keys: %s in store %s", keys, storeId)); } return token; }); }  @Override String acquire(final List<String> keys, final String storeId, final long expiration); @Override boolean release(final List<String> keys, final String storeId, final String token); @Override boolean refresh(final List<String> keys, final String storeId, final String token, final long expiration);  }
@Test public void shouldNotRetryWhenFirstAttemptIsSuccessful() { when(lock.acquire(anyList(), anyString(), anyLong())) .thenReturn("abc"); final var retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); final var retriableLock = new RetriableLock(lock, retryTemplate); final var token = retriableLock.acquire(List.of("key"), "defaultStore", 1000L); assertThat(token).isEqualTo("abc"); }
@Test public void shouldRetryWhenFirstAttemptIsNotSuccessful() { when(lock.acquire(anyList(), anyString(), anyLong())) .thenReturn(null) .thenReturn("abc"); final var retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); final var retriableLock = new RetriableLock(lock, retryTemplate); final var token = retriableLock.acquire(List.of("key"), "defaultStore", 1000L); assertThat(token).isEqualTo("abc"); verify(lock, times(2)).acquire(anyList(), anyString(), anyLong()); }
@Test(expected = LockNotAvailableException.class) public void shouldFailRetryWhenFirstAttemptIsNotSuccessful() { when(lock.acquire(anyList(), anyString(), anyLong())) .thenReturn(null); final var retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); final var retriableLock = new RetriableLock(lock, retryTemplate); final var token = retriableLock.acquire(List.of("key"), "defaultStore", 1000L); assertThat(token).isEqualTo("abc"); }