Last active
December 17, 2015 09:08
-
-
Save aogonevskiy/5584889 to your computer and use it in GitHub Desktop.
Google Guava CacheBuilder example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.cache.*; | |
import java.util.BitSet; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.TimeUnit; | |
public class Test { | |
private LoadingCache<String, BitSet> cache = null; | |
RemovalListener<String, BitSet> removalListener = new RemovalListener<String, BitSet>() { | |
public void onRemoval(RemovalNotification<String, BitSet> removal) { | |
BitSet b = removal.getValue(); | |
// to something | |
System.out.println("Removing the key = " + removal.getKey()); | |
} | |
}; | |
public Test(){ | |
this.cache = CacheBuilder.newBuilder() | |
//.maximumSize(10000) | |
.expireAfterWrite(10, TimeUnit.MINUTES) | |
.softValues() | |
.removalListener(removalListener) | |
.build( | |
new CacheLoader<String, BitSet>() { | |
public BitSet load(String key) throws Exception { | |
return loadBitset(key); | |
} | |
}); | |
} | |
private BitSet loadBitset(String key) { | |
return new BitSet(1000000); | |
} | |
public static void main(String argv[]) throws ExecutionException, InterruptedException { | |
Test t = new Test(); | |
// Thread.sleep(10000); | |
System.out.println("1 = " + t.cache.size()); | |
for (int i = 0; i < 2000 ; i++) { | |
t.cache.get(String.valueOf(i)); | |
} | |
System.out.println("2 = " + t.cache.size()); | |
// Thread.sleep(10000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment