KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > caching > Fibonacci


1 /**************************************************************************************
2  * Copyright (c) Jonas BonŽr, Alexandre Vasseur. All rights reserved. *
3  * http://aspectwerkz.codehaus.org *
4  * ---------------------------------------------------------------------------------- *
5  * The software in this package is published under the terms of the BSD-style license *
6  * a copy of which has been included with this distribution in the license.txt file. *
7  **************************************************************************************/

8 package examples.caching;
9
10 import java.util.HashMap JavaDoc;
11 import java.util.Map JavaDoc;
12
13 import org.codehaus.aspectwerkz.joinpoint.JoinPoint;
14 import org.codehaus.aspectwerkz.joinpoint.MethodRtti;
15 import org.codehaus.aspectwerkz.joinpoint.Rtti;
16
17 /**
18  * Sample that calculates fibonacci number naively, uses an inner aspect to cache redundant
19  * calculations.
20  *
21  * @author <a HREF="mailto:jboner@codehaus.org">Jonas BonŽr </a>
22  */

23 public class Fibonacci {
24
25     // naive implementation of fibonacci, resulting in a lot
26
// of redundant calculations of the same values.
27
public static int fib(int n) {
28         if (n < 2) {
29             System.err.println(n + ".");
30             return 1;
31         } else {
32             System.err.print(n + ",");
33             return fib(n - 1) + fib(n - 2);
34         }
35     }
36
37     public static void main(String JavaDoc[] args) {
38         System.err.println("fib(10) = " + fib(10));
39     }
40
41     /**
42      * Caches redundant fibonacci calculations.
43      */

44     public static class FibonacciCacheAspect {
45
46         private Map JavaDoc m_cache = new HashMap JavaDoc();
47
48         /**
49          * @Around execution(int *..Fibonacci.fib(int))
50          */

51         public Object JavaDoc cache(final JoinPoint joinPoint) throws Throwable JavaDoc {
52             MethodRtti mrtti = (MethodRtti) joinPoint.getRtti();
53             Integer JavaDoc parameter = (Integer JavaDoc) mrtti.getParameterValues()[0];
54             Integer JavaDoc cachedValue = (Integer JavaDoc) m_cache.get(parameter);
55             if (cachedValue == null) {
56                 Object JavaDoc newValue = joinPoint.proceed(); // not found => calculate
57
m_cache.put(parameter, newValue);
58                 return newValue;
59             } else {
60                 System.out.println("using cache: " + cachedValue);
61                 return cachedValue; // return cached value
62
}
63         }
64     }
65 }
66
67
Popular Tags