reference:http://java.dzone.com/articles/caching-best-practices

There is an irresistible attraction to writing custom caching solutions, since it seems to be the easiest path to “improving” the overall application performance. Well, caching is a great technique, but there are few steps to consider before even considering it.

Best practices

  1. A key/value collection is not a Cache

    Almost all projects I worked on have been using some sort of custom caching solutions, built on top of Java Maps. A Map is not an out-of-the-box Caching solution, since a Cache is more than a key/value store. A Cache also requires:

    • eviction policies
    • max size limit
    • persistent store
    • weak references keys
    • statistics

    A Java Map doesn’t offer these features and you shouldn’t spend your customer’s money to write a custom cache solution either. You should choose a professional cache like EHCache or Guava Cache, which are both powerful and simple to use. Those tools are constantly tested by all those projects employing them, so the code quality is higher than most custom built solutions.

  2. Use a cache abstraction layer

    A very flexible solution is the Spring Cache abstraction. The @Cacheableannotation allows you to separate the business logic code from the caching cross-cutting concern. The caching solution is therefore configurable and it’s not going to pollute your business methods.

  3. Beware of the caching overhead

    Every API has a cost and caching is no different. If you cache a web service or an expensive database call, then the overhead is probably negligible. If you use a local cache for a recursive algorithm, you need to be aware of the overall caching solution overhead. Even the Spring cache abstraction has an overhead, so make sure the benefits outweigh the costs.

  4. If your database queries are slow, the cache should be your last resort

    If you use an ORM tool like Hibernate, that’s the first place where your optimization process should start from. Make sure the fetching strategy is properly designed, and you don’t suffer from N+1 query problems. You could also assert the SQL statement count to validate the ORM generated queries.

    When you’re done optimizing your ORM SQL query generation, you should check your database for slow queries. Make sure all indexes are in place and that your SQL queries are effective.
    The indexes must always fit into RAM, otherwise you will hit the more expensive SSD or HDD. Your database has the ability to cache query results, so take advantage of it.

    If the data set is large and the growth rate is high you could horizontally scale it on multiple shards.

    If all of those actions are not enough, you may consider a professional caching solution such as Memcached.

  5. What about data consistency?

    When you start using a cache in front of your business layer, the data consistency constraint is being challenged. The benefits of ACID may be compromised if the cache is not properly synchronized with the database. This is like keeping a denormalized form of your actual data. If a root entity changes it may affect a large portion of your cache. If you discard the cache entries, all the caching benefits are lost. If you asynchronously update the cache entries you loose the strong data consistency, leaving you with an eventual consistent data model.

Playing time

Inspired by this very interesting post on the Java 8 computeIfAbsent Map addition, I decided to present you a Guava Cache alternative that has the following advantages:

  1. there is a fixed cache size of 2 entries
  2. it works with Java 1.6
01.private LoadingCache<Integer, Integer> fibonacciCache = CacheBuilder.newBuilder()
02..maximumSize(2)
03..build(new CacheLoader<Integer, Integer>() {
04.public Integer load(Integer i) {
05.if (i == 0)
06.return i;
07.if (i == 1)
08.return 1;
09.LOGGER.info("Calculating f(" + i + ")");
10.return fibonacciCache.getUnchecked(i - 2) + fibonacciCache.getUnchecked(i - 1);
11.}
12.});
13. 
14.@Test
15.public void test() {
16.for (int i = 0; i < 10; i++) {
17.LOGGER.info("f(" + i + ") = " + fibonacciCache.getUnchecked(i));
18.}
19.}

And the output is:

01.INFO  [main]: FibonacciGuavaCacheTest - f(0) = 0
02.INFO  [main]: FibonacciGuavaCacheTest - f(1) = 1
03.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(2)
04.INFO  [main]: FibonacciGuavaCacheTest - f(2) = 1
05.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(3)
06.INFO  [main]: FibonacciGuavaCacheTest - f(3) = 2
07.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(4)
08.INFO  [main]: FibonacciGuavaCacheTest - f(4) = 3
09.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(5)
10.INFO  [main]: FibonacciGuavaCacheTest - f(5) = 5
11.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(6)
12.INFO  [main]: FibonacciGuavaCacheTest - f(6) = 8
13.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(7)
14.INFO  [main]: FibonacciGuavaCacheTest - f(7) = 13
15.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(8)
16.INFO  [main]: FibonacciGuavaCacheTest - f(8) = 21
17.INFO  [main]: FibonacciGuavaCacheTest - Calculating f(9)
18.INFO  [main]: FibonacciGuavaCacheTest - f(9) = 34

Code available on GitHub.

 

Published at DZone with permission of Vlad Mihalcea, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Scalability and better performance are constant concerns for the developer and operations manager. New Relic and AppDynamics are dedicated to performance education as the supporters of the Performance Zone. Try both AppDynamics' fully-featured performance tool for Java, .NET, & PHP, or New Relic's free lite version to see which tool is the solution for your organization. One thing you can't afford, is no monitoring at all.

Caching Best Practices--reference的更多相关文章

  1. Cheatsheet: 2014 03.01 ~ 03.31

    .NET Should I be concerned about PDB files? async and await -Simplified-Internals Web Performance tr ...

  2. 《转》前端性能优化----yahoo前端性能团队总结的35条黄金定律

    除了自己总结:1. 减少http请求,2.压缩并优化js/css/image 3.尽量静态页面,从简原则 4.代码规范(详见:个人知识体系思维导图) 从yahoo 新学到的: 网页内容 减少http请 ...

  3. Service Worker和HTTP缓存

    很多人,包括我自己,初看Service Worker多一个Cache Storage的时候,就感觉跟HTTP长缓存没什么区别. 例如大家讲的最多的Service Worker能让网页离线使用,但熟悉H ...

  4. HTTP 缓存相关

    网络中数据传输是很耗时的,数据要在漫长的路径中奔波,客户端在数据完整到达前只能等待.如果能够复用已经请求过的资源,势必会让整个页面加载高效许多.这可以通过合理地设置服务器的缓存,与浏览器的缓存机制配合 ...

  5. Known BREAKING CHANGES from NH3.3.3.GA to 4.0.0

    Build 4.0.0.Alpha1 =============================   ** Known BREAKING CHANGES from NH3.3.3.GA to 4.0. ...

  6. JavaScript性能优化【转载】

    你愿意为打开一个网页等待多长时间?我一秒也不愿意等.但是事实上大多数网站在响应速度方面都让人失望.现在越来越多的人开始建立自己的网站,博客,你的网页响应速度如何呢?在这篇文章中我们来介绍一下提高网页性 ...

  7. http网页性能最佳实践

    你愿意为打开一个网页等待多长时间?我一秒也不愿意等.但是事实上大多数网站在响应速度方面都让人失望.现在越来越多的人开始建立自己的网站,博客,你的网页响应速度如何呢?在这篇文章中我们来介绍一下提高网页性 ...

  8. Collection View Programming Guide for iOS---(七)---Custom Layouts: A Worked Example

    Custom Layouts: A Worked Example Creating a custom collection view layout is simple with straightfor ...

  9. 缓存篇~第六回 Microsoft.Practices.EnterpriseLibrary.Caching实现基于方法签名的数据集缓存

    返回目录 这一讲中主要是说EnterpriseLibrary企业级架构里的caching组件,它主要实现了项目缓存功能,它支持四种持久化方式,内存,文件,数据库和自定义,对于持久化不是今天讨论的重要, ...

  10. 错误:创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching,

    问题: 错误:创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching ...

随机推荐

  1. HDU ACM 1325 / POJ 1308 Is It A Tree?

    Is It A Tree? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  2. cocos2d-html5在cocos2d-x里面打包编译

    main.cpp打开USE_WIN32_CONSOLE输出 #include "main.h" #include "AppDelegate.h" #includ ...

  3. mysql基础知识(3)--创建

    创建表: 基本形式 create  table  [if not  exists] 表名(字段列表, [约束或索引列表]) [表选项列表]; 说明:列表都是表示“多个”,相互之间用逗号分开. 字段基本 ...

  4. Fast-paced Multiplayer

    http://www.gabrielgambetta.com/fpm1.html —————————————————————————————————————————————————————— Fast ...

  5. Mysql SQL优化&执行计划

    SQL优化准则 禁用select * 使用select count(*) 统计行数 尽量少运算 尽量避免全表扫描,如果可以,在过滤列建立索引 尽量避免在where子句对字段进行null判断 尽量避免在 ...

  6. chrome浏览器插件window resizer调试webapp页面大小

    chrome浏览器插件window resizer可以调整当前浏览器分辨率大小 可以自定义大小,以适合于andorid和iphone设备

  7. Python基础 字符串的魔法

    capitalize(self) 返回值:将字符串的第一个首字母变成大写,其他字母变小写 s = 'hello World' ss = s.capitalize() print(ss) Hello w ...

  8. Codeforces 444 C. DZY Loves Colors (线段树+剪枝)

    题目链接:http://codeforces.com/contest/444/problem/C 给定一个长度为n的序列,初始时ai=i,vali=0(1≤i≤n).有两种操作: 将区间[L,R]的值 ...

  9. HDU 5776 sum (前缀和)

    题意:给定 n 个数,和 m,问你是不是存在连续的数和是m的倍数. 析:考虑前缀和,如果有两个前缀和取模m相等,那么就是相等的,一定要注意,如果取模为0,就是真的,不要忘记了,我当时就没记得.... ...

  10. test是否被执行?

    procedure TForm2.Button1Click(Sender: TObject);  function test(value:boolean):boolean;  begin    res ...