-
Notifications
You must be signed in to change notification settings - Fork 1
/
GuavaCache.java
68 lines (62 loc) · 2.49 KB
/
GuavaCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package DBClients;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Created by deepak.jayaprakash on 15/11/18.
*/
public class GuavaCache {
@Test
public void sizeBasedEviction() {
LoadingCache<Integer, String> idNameCache = CacheBuilder.newBuilder()
.maximumSize(3)
.build(new CacheLoader<Integer, String>() {
@Override
public String load(Integer integer) throws Exception {
return "value" + String.valueOf(integer);
}
});
try {
System.out.println(idNameCache.get(1));
System.out.println(idNameCache.get(2));
System.out.println(idNameCache.get(3));
Assert.assertEquals(idNameCache.size(), 3);
System.out.println(idNameCache.get(4));
Assert.assertEquals(idNameCache.size(), 3);
Assert.assertNull(idNameCache.getIfPresent(1));
} catch (ExecutionException e) {
System.out.println("cache miss for " + e);
}
}
@Test
public void timeBasedEviction() {
LoadingCache<Integer, String> idNameCache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.SECONDS) // expire after read
.expireAfterWrite(1, TimeUnit.SECONDS) // expire after write
.build(new CacheLoader<Integer, String>() {
@Override
public String load(Integer integer) throws Exception {
return "value" + String.valueOf(integer);
}
});
try {
System.out.println(idNameCache.get(1));
System.out.println(idNameCache.get(2));
System.out.println(idNameCache.get(3));
System.out.println(idNameCache.get(4));
Assert.assertEquals(idNameCache.size(), 4);
Thread.sleep(3500);
Assert.assertNull(idNameCache.getIfPresent(1));
Assert.assertNull(idNameCache.getIfPresent(2));
Assert.assertNull(idNameCache.getIfPresent(3));
Assert.assertNull(idNameCache.getIfPresent(4));
Assert.assertEquals(idNameCache.size(), 0);
} catch (Exception e) {
System.out.println(e);
}
}
}