01: /**************************************************************************************
02: * Copyright (c) Jonas BonŽr, Alexandre Vasseur. All rights reserved. *
03: * http://aspectwerkz.codehaus.org *
04: * ---------------------------------------------------------------------------------- *
05: * The software in this package is published under the terms of the BSD-style license *
06: * a copy of which has been included with this distribution in the license.txt file. *
07: **************************************************************************************/package examples.caching;
08:
09: import java.util.HashMap;
10: import java.util.Map;
11:
12: import org.codehaus.aspectwerkz.joinpoint.JoinPoint;
13: import org.codehaus.aspectwerkz.joinpoint.MethodRtti;
14: import org.codehaus.aspectwerkz.joinpoint.Rtti;
15:
16: /**
17: * Sample that calculates fibonacci number naively, uses an inner aspect to cache redundant
18: * calculations.
19: *
20: * @author <a href="mailto:jboner@codehaus.org">Jonas BonŽr </a>
21: */
22: public class Fibonacci {
23:
24: // naive implementation of fibonacci, resulting in a lot
25: // of redundant calculations of the same values.
26: public static int fib(int n) {
27: if (n < 2) {
28: System.err.println(n + ".");
29: return 1;
30: } else {
31: System.err.print(n + ",");
32: return fib(n - 1) + fib(n - 2);
33: }
34: }
35:
36: public static void main(String[] args) {
37: System.err.println("fib(10) = " + fib(10));
38: }
39:
40: /**
41: * Caches redundant fibonacci calculations.
42: */
43: public static class FibonacciCacheAspect {
44:
45: private Map m_cache = new HashMap();
46:
47: /**
48: * @Around execution(int *..Fibonacci.fib(int))
49: */
50: public Object cache(final JoinPoint joinPoint) throws Throwable {
51: MethodRtti mrtti = (MethodRtti) joinPoint.getRtti();
52: Integer parameter = (Integer) mrtti.getParameterValues()[0];
53: Integer cachedValue = (Integer) m_cache.get(parameter);
54: if (cachedValue == null) {
55: Object newValue = joinPoint.proceed(); // not found => calculate
56: m_cache.put(parameter, newValue);
57: return newValue;
58: } else {
59: System.out.println("using cache: " + cachedValue);
60: return cachedValue; // return cached value
61: }
62: }
63: }
64: }
|