FileDocCategorySizeDatePackage
Fibonacci.javaAPI DocExample1605Sat Apr 17 23:40:42 BST 2004javathreads.examples.ch08.example6

Fibonacci

public class Fibonacci extends Object

Fields Summary
private ConcurrentMap
values
Constructors Summary
Methods Summary
public intcalculate(int x)


        
        if (x < 0)
            throw new IllegalArgumentException("positive numbers only");
        if (x <= 1)
            return x;
        return calculate(x-1) + calculate(x-2);
    
public intcalculateOnlyWithCache(int x)

        Integer v1 = values.get(new Integer(x-1));
        Integer v2 = values.get(new Integer(x-2));
        Integer key = new Integer(x);
        Integer result = values.get(key);
        
        if (result != null)
            return result.intValue();

        if ((v1 == null) || (v2 == null))
            throw new IllegalArgumentException("values not in cache");
        result = new Integer(v1.intValue() + v2.intValue());

        values.putIfAbsent(key, result);
        return result.intValue();
    
public voidcalculateRangeInCache(int x, int y)

        calculateWithCache(x++);
        calculateWithCache(x++);
        while (x <= y) {
            calculateOnlyWithCache(x++);
        }
    
public intcalculateWithCache(int x)

        Integer key = new Integer(x);
        Integer result = values.get(key);

        if (result == null) {
            result = new Integer(calculate(x));
            values.putIfAbsent(key, result);
        }
        return result.intValue();