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. BOX2D测试

    ; ; Box2DTestLayer = cc.Layer.extend({ world:null, //GLESDebugDraw *m_debugDraw; ctor:function () { ...

  2. 阿里云开放服务oss的api

    http://imgs-storage.cdn.aliyuncs.com/help/oss/OSS_API_20131015.pdf?spm=5176.383663.5.23.JQjiIK&f ...

  3. 创建并使用Windows Azure虚拟机模板

    在现实的IaaS应用中,往往会创建自己的虚拟机映像模板,以满足快速应用部署的目标,如预先配置好某些应用.管理与监控管理等. 1.登录到Windows Azure Dashboard中创建一个做为模板的 ...

  4. 2013 ACM/ICPC南京邀请赛B题(求割点扩展)

    题目链接:http://icpc.njust.edu.cn/Contest/194/Problem/B B - TWO NODES 时间限制: 10000 MS 内存限制: 65535 KB 问题描述 ...

  5. 代码中设置excel自定义格式为[红色]的处理方法

    有时候,excel的自定义格式设置时 ,会遇到需要设置为¥#,##0;[红色]¥-#,##0的格式. 其中会带一个颜色标记,但是如果这样的一句代码,放在英文版的Office里面,就失效了,因为英文版应 ...

  6. AcceptEx编辑

    Windows套接字AcceptEx函数接受一个新的连接,返回本地和远程地址,并接收由客户端应用程序发送的第一块数据.Windows 95/98不支持AcceptEx函数. 平台SDK:Windows ...

  7. android 解释dp,px,pt,sp单位

    1.dp(dip):不同设备有不同的显示效果,这个和设备硬件有关系,一般我们为了支持WVGA,HVGA和QVGA对剑使用这个,它是不依赖像素的 2.px:pixels(像素),不同设备显示效果相同,一 ...

  8. HTML5 ajax上传附件

    var fd = new FormData();             fd.append('/*键值*/', this.files[0]);var xhr = new XMLHttpRequest ...

  9. table布局 height=100%无效分析

    (从死了一次又一次终于挂掉的百度空间中抢救出来的,发表日期 2014-08-11) 原文链接:http://www.cnblogs.com/gaojun/archive/2012/05/07/2487 ...

  10. JS 执行环境与作用域链

    1.执行环境 JavaScript 代码都是在执行环境中被执行的.执行环境是一个概念,一种机制,用来完成JavaScript运行时在作用域.生命周期等方面的处理,它定义了变量或函数是否有权访问其他数据 ...