惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
H
Help Net Security
Last Week in AI
Last Week in AI
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
B
Blog
C
Check Point Blog
T
Tailwind CSS Blog
云风的 BLOG
云风的 BLOG
D
Docker
Recent Announcements
Recent Announcements
Vercel News
Vercel News
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
月光博客
月光博客
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
The Register - Security
The Register - Security
V
Visual Studio Blog
F
Full Disclosure
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
PCI Perspectives
PCI Perspectives
Cisco Talos Blog
Cisco Talos Blog
博客园 - Franky
D
DataBreaches.Net
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
P
Palo Alto Networks Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
T
Tenable Blog
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens Prisoner's Dilemma Climbing No More The Weekly Win Mevlana Candy Brewing Turkish Tea Onboarding Your Engineering Manager Technical Deep Dives Yapay Zekâ Çağında Bilgisayar Mühendisliği Building Remote Teams From Idea to Launch in 2 Weeks Reflecting on Software Engineering Handbook Representing the Business New Manager Survival Guide Take Self Reviews Seriously Chasing Real Respect The Invisible Difference Learning the Johari Window Management is a Lonely Place Simple Task Management AI Balance in Work PIP Manager Insights Engineering Manager Interview Preparation Work-Life Balance as a Manager Bridging the Management Disconnect Tech Hiring Bubble Bursts Traits for EMs Simple Acts of Recognition Matter The Question I Ask Every New Report The Reality of an Employer's Market Bridging Ideals and Reality Hiring Red Flags Why The Godfather Is So Damn Good Subteam Tenets No Fluff Please Losing a Top Performer Balancing Act of Reliability Building Trust in Engineering Teams Ideal Number of Direct Reports Overriding a People Leader’s Decision From Misperception to Promotion Perception vs Perspective Setting Goals From Engineer to Manager Getting Delegation Right Interviewing Your Future Boss Celebrating Our Book in Iceland Operational Skills Needed On Writing Software Engineering Handbook Charlie Munger Quotes Working with Dependencies From Las Vegas to Canyons Navigating Layoffs Handling Competitive Dynamics A Weekend Getaway to Malta Engineering Health Essentials Should Dev Managers Code? Confronting the Life on Pause Winning Eleven Kindness is A Choice Bireysel Katılımcılar ve Yöneticiler Leading from Where You Are The Subtle Art of Listening Coding in Leadership The Power of Consistency The Making of a Leader The Path to Leadership Embracing TikTok Talent Sourcing Journey Leading Self Managing Teams Cracking Coding Bottlenecks
Caching With Guava
Yusuf Aytas · 2012-05-24 · via Yusuf Aytas

Published · 3 min read

In computer science, cache is a component that is used to speed up data retrieval in general. The data stored in cache is limited so a given query can hit or miss the data that we are looking for. Caches are generally small in terms of storage because we want it to be fast. There are lots of cache types like CPU Cache, Disk Cache, Web Cache and more. There are several implementations of caches spreading out simple caches to complex caches in Java. Google's guava library also provides cache mechanism. In this post, we will consider guava cache mechanism and some coding examples for guava.

Guava cache is a simple library that provides flexible and powerful caching features. As guava developers explain, guava cache can be used when fast access needed and when values retrieved multiple times. Generally those needs described above can be catered by  ConcurrentMap implementation; however, a cache removes entries automatically by given constraints like time, size and etc. As a result, automatic eviction of entries makes cache better in terms of load-balancing. To do so guava library implements cache interface described below.

Guava Library cache interface allows standard caching operations like get, put and invalidate. Get operation returns the value associated by the key, put operation stores value associated by the key and invalidate operation discards the value associated with the key. In order to get values that are not currently in cache, there is CacheLoader interface that implements load operation. Moreover, if one want to modify the value that is returned, he can make use of Callable interface that implements call(modifies returned value) operation. Let's move the coding part.

In our first class, we implement a cache that uses keys to retrieve a person. We define out cache to have a maximum size of 100(it is a very low value, generally higher values are preferred) person. We want to expire keys after 10 seconds of latest access. Moreover, we load our keys by the help of a CacheLoader defined by loader. Lastly, we add a removal listener to catch removal events. In this implementation, we have just used some of the functions that are provided by guava. However, we could use other functions like refreshAfterWrite, expireAfterWrite and so on.

package com.yusufaytas.examples.guava;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;

@Component
public class PersonCache {

	LoadingCache cache;

	@Autowired
	PersonCacheLoader loader;

	@Autowired
	PersonRemovalListener listener;

	public void init(){
		cache = CacheBuilder.newBuilder().
				maximumSize(100).
				expireAfterAccess(10, TimeUnit.SECONDS).
				removalListener(listener).
				build(loader);
	}

	public Person get(String key) throws ExecutionException{
		return cache.get(key);
	}
}

In PersonCacheLoader class, we implement CacheLoader interface. We simply load Person by the help of PersonSerializer which have deserialize method uses key to create Person from file.

package com.yusufaytas.examples.guava;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.cache.CacheLoader;

@Component
public class PersonCacheLoader extends CacheLoader{

	@Autowired
	PersonSerializer personSerializer;

	public Person load(String key) throws Exception {
		return personSerializer.deserialize(key);
	}
}

We have lastly a removal listener that logs the removed Person's key.

package com.yusufaytas.examples.guava;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

@Component
public class PersonRemovalListener implements RemovalListener{

	Logger logger = LoggerFactory.getLogger(PersonRemovalListener.class);

	public void onRemoval(RemovalNotification notification) {
		logger.info("Person associated with the key("+
				notification.getKey()+ ") is removed.");
	}

}

In implementation of those classes we have used spring framework which handles dependencies by the help of annotations(Autowired,Component). The ones who are not familiar with spring can use the classes by creating them manually. Consequently, we tried to talk about general cache, guava cache and give sample code snippets here.