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. cocos2d 设置按钮不可用

    需要两步设置按钮变灰,然后不可点击 btnBuy.setBright(false); btnBuy.setTouchEnabled(false); 或者直接不显示按钮 btnBuy.setEnable ...

  2. C++11之使用或禁用对象的默认函数

    [C++11之使用或禁用对象的默认函数] C++11 允许显式地表明采用或拒用编译器提供的内置函数.例如要求类型带有默认构造函数,可以用以下的语法: 另一方面,也可以禁止编译器自动产生某些函数.如下面 ...

  3. tomcat的 JNDI 配置

    tomcat的conf/server.xml 配置 尽量用简单版 <Context path="/cas" docBase="D:\YC\zqV7\cas\WebR ...

  4. Jsp页面设计易忘点

    文本标签: <b>文本加粗 <i>斜体 <u>下划线 <sub>作为下标 <sup>作为上标 样式: italic;斜体 text-deco ...

  5. mysql kill操作

    KILL语法 KILL [CONNECTION | QUERY] thread_id 每个与mysqld的连接都在一个独立的线程里运行,您可以使用SHOW PROCESSLIST语句查看哪些线程正在运 ...

  6. [源码分享] HIVE表数据量统计&邮件

    概要: 计算HIVE BI库下每天数据表总大小及增量 输出: 总大小:xxxG 日同比新增数据量:xxxG 周同比新增数据量:xxxG 月同比新增数据量:xxxG 总表数:xxx 日新增表数:xxx ...

  7. oracle客户端安装及Plsql devloper连接

    1)安装Oracle 11g 64位 2)安装32位的Oracle客户端( instantclient-basic-win32-11.2.0.1.0)下载instantclient-basic-win ...

  8. EasyUI Accordion下的Panel面板初始化时全部折叠

    EasyUI Accordion下的Panel面板有一个属性:selected,默认值为:false.初始化时,若设置'selected:true',则面板默认打开,效果如下: <div tit ...

  9. javascript自执行函数为什么要把windows作为参数传进去

    http://segmentfault.com/q/1010000000311686 (function (window, $, undefined) { play=function(){ $(&qu ...

  10. 给Oracle锁住的行解锁

    1.找出数据库的serial#,以备杀死: select t2.username,t2.sid,t2.serial#,t2.logon_time from v$locked_object t1,v$s ...