Skip to content

Commit

Permalink
Add a unit test for CachedCallable
Browse files Browse the repository at this point in the history
  • Loading branch information
afeinberg committed Aug 29, 2011
1 parent 2ab4746 commit a2efaf4
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/java/voldemort/utils/CachedCallable.java
Expand Up @@ -11,21 +11,28 @@ public class CachedCallable<T> implements Callable<T> {

private final Callable<T> inner;
private final long ttlMs;
private final Time time;
private final AtomicReference<T> valueRef;

private volatile long lastCalledMs;

public CachedCallable(Callable<T> inner,
long ttlMs) {
this(inner, ttlMs, SystemTime.INSTANCE);
}

public CachedCallable(Callable<T> inner,
long ttlMs,
Time time) {
this.inner = inner;
this.ttlMs = ttlMs;
this.time = time;
valueRef = new AtomicReference<T>();
}


public T call() throws Exception {
T value = valueRef.get();
long now = System.currentTimeMillis();
long now = time.getMilliseconds();
if(value == null || now - lastCalledMs > ttlMs) {
T newValue = inner.call();
if(valueRef.compareAndSet(value, newValue)) {
Expand Down
58 changes: 58 additions & 0 deletions test/unit/voldemort/utils/CachedCallableTest.java
@@ -0,0 +1,58 @@
package voldemort.utils;


import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import voldemort.MockTime;

import java.util.concurrent.Callable;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class CachedCallableTest {

private static final long CACHE_TTL_MS = 1000;
private static final long CALL_RESULT = 0xdeaddeadl;

@Mock
private Callable<Long> inner;

private CachedCallable<Long> cachedCallable;
private MockTime mockTime;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(inner.call()).thenReturn(CALL_RESULT);
mockTime = new MockTime();
cachedCallable = new CachedCallable<Long>(inner,
CACHE_TTL_MS,
mockTime);
}

@Test
public void testCall() throws Exception {
assertEquals((long) cachedCallable.call(), CALL_RESULT);
}

@Test
public void testCaching() throws Exception {
cachedCallable.call();
cachedCallable.call();
verify(inner, times(1)).call();
}

@Test
public void testTtl() throws Exception {
cachedCallable.call();
cachedCallable.call();
verify(inner, times(1)).call();
mockTime.addMilliseconds(1001);
when(inner.call()).thenReturn(CALL_RESULT + 1l);
assertEquals((long) cachedCallable.call(), CALL_RESULT + 1l);
verify(inner, times(2)).call();
}
}

0 comments on commit a2efaf4

Please sign in to comment.