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. Ubuntu关闭图形界面

    方法一 sudo /etc/init.d/lightdm stop 方法二 init 3 关闭图形界面 init 5 开启图形界面

  2. jBox使用方法

    1.引入jquery文件 2.引入css和jBox文件 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml& ...

  3. <转>Linux环境进程间通信(二): 信号(上)

    原文链接:http://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html 原文如下: 一.信号及信号来源 信号本质 信号是在软件层 ...

  4. 存量数据处理结果查询.txt

    请求报文:<?xml version="1.0" encoding="UTF-8"?><PDL><PDL-Head>< ...

  5. LightOJ 1112 Curious Robin Hood (单点更新+区间求和)

    http://lightoj.com/volume_showproblem.php?problem=1112 题目大意: 1 i        将第i个数值输出,并将第i个值清0 2 i v     ...

  6. sql2008来远程访问sql2005数据库服务器

    今天搞了一个下午终于搞定了数据库的远程访问.其基本步骤如下: sql2008的配置: sql server 2008默认是不允许远程连接的,sa帐户默认禁用的,如果想要在本地用SSMS连接远程服务器上 ...

  7. [置顶] 小强的HTML5移动开发之路(9)——坦克大战游戏3

    上一篇我们创建了敌人的坦克和自己的坦克,接下来就应该让坦克发子弹了,我们下面来看一下如何让我们的坦克发出子弹. 前面我们用面向对象的思想对Tank进行了封装,又利用对象冒充实现了我们的坦克和敌人的坦克 ...

  8. 网页上的JS call Unity3d里的function——SendMessage

    注意: sendmessage只可以从网页发信息到unity游戏里,但是没有返回值 只可以发布三种类型的data,不可以其他复杂的强类型 发信息的时不会做编译检测 SendMessage Workfl ...

  9. Spring MVC体系结构

    [Spring MVC类图]<Spring实战>中:<Spring3.0就这么简单>中:[http://blog.csdn.net/gstormspire/article/de ...

  10. Jquery 提示

    1  文字提示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...