org.codehaus.groovy.runtime.memoize.Memoize Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.runtime.memoize;
import groovy.lang.Closure;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Arrays.copyOf;
/**
* Implements memoize for Closures.
* It is supposed to be used by the Closure class itself to implement the memoize() family of methods.
*
* @author Vaclav Pech
*/
public abstract class Memoize {
/**
* A place-holder for null values in cache
*/
private static final MemoizeNullValue MEMOIZE_NULL = new MemoizeNullValue();
/**
* Creates a new closure delegating to the supplied one and memoizing all return values by the arguments.
*
* The supplied cache is used to store the memoized values and it is the cache's responsibility to put limits
* on the cache size or implement cache eviction strategy.
* The LRUCache, for example, allows to set the maximum cache size constraint and implements
* the LRU (Last Recently Used) eviction strategy.
*
* @param cache A map to hold memoized return values
* @param closure The closure to memoize
* @param The closure's return type
* @return A new memoized closure
*/
public static Closure buildMemoizeFunction(final MemoizeCache