Skip to content

Instantly share code, notes, and snippets.

@horiga
Created September 11, 2013 10:38
Show Gist options
  • Save horiga/6521940 to your computer and use it in GitHub Desktop.
Save horiga/6521940 to your computer and use it in GitHub Desktop.
A simple java cache. use the 'guava-libraries'
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaCacheTest {
public static class Value {
String id;
String createYmdt;
public Value() {
this.id = UUID.randomUUID().toString();
this.createYmdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
public String toString() {
return "[" + createYmdt + "]:" + id;
}
}
public static Cache<String, Value> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.expireAfterWrite(3000, TimeUnit.MILLISECONDS)
.build();
public static void main(String[] args) {
System.out.println("startUp");
try {
Value val = cache.getIfPresent("key1");
if ( val == null) cache.put("key1", new Value());
// If maximum cache put
for ( int n=0; n<15; n++) {
try {
cache.put("k" + n, new Value());
System.out.println("cache size=" + cache.size());
} catch ( Exception e) {
// If maximum put. not exception occurred.
e.printStackTrace();
}
}
for ( int i=0; i<30; i++) {
Value v = cache.getIfPresent("key1");
if ( v != null) {
System.out.println(String.format("(Hit) %d - %s", i, v));
} else {
System.out.println("(Refresh)");
cache.put("key1", new Value());
}
System.out.println("cache size=" + cache.size());
Thread.sleep(1000);
}
cache.cleanUp();
System.out.println("cleanUp");
} catch ( Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment