Cache with Suppliers

先前曾使用Guava cache建立Map cache,而單一值的cache也被常常使用。

以下兩個範例,testSuppliersCache示範了使用方式,而testSuppliersExpiredCache增加了時間限制:

public class TestSuppliers {
	private int count = 0;
	@Test
	public void testSuppliersCache(){
		Supplier<String> s = Suppliers.memoize(this::getMemoize);
		Assert.assertEquals( 0, count);
		Assert.assertEquals("testMemoize", s.get());
		Assert.assertEquals( 1, count);
		Assert.assertEquals("testMemoize", s.get());
		Assert.assertEquals( 1, count);
	}	
 
	@Test
	public void testSuppliersExpiredCache() throws Exception {
		Supplier<String> s = Suppliers.memoizeWithExpiration(this::getMemoize, 3, TimeUnit.SECONDS);
		Assert.assertEquals( 0, count);
		Assert.assertEquals("testMemoize", s.get());
		Assert.assertEquals( 1, count);
		Thread.sleep(3200);
		Assert.assertEquals("testMemoize", s.get());
		Assert.assertEquals( 2, count);
	}
 
	public String getMemoize(){
		count++;
		return "testMemoize";
	}
}

使用的最大好處,就是可以省去像下面這樣的程式碼,直接交由Supplier決定:

private CacheObject mCache = null;
 
public void doSomething(){
	if( mCache == null ) {
		// ... init mCache
	}
	// do something with mCache 
}