OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
180 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils.cc;
15
 
16
import org.openconcerto.utils.CollectionUtils;
17
import org.openconcerto.utils.cache.LRUMap;
18
import org.openconcerto.utils.cache.Memoizer;
19
 
20
import java.util.Map;
21
 
22
import net.jcip.annotations.NotThreadSafe;
23
 
24
/**
25
 * Allow to cache the result of a function.
26
 *
27
 * @author sylvain
28
 *
29
 * @param <K> the type of the function parameter.
30
 * @param <V> the type of the function result.
31
 * @param <X> the type of the function exception.
32
 * @see LRUMap to limit cache size.
33
 * @see Memoizer for a thread-safe class with concurrent creation of entries.
34
 */
35
@NotThreadSafe
36
public class CachedTransformer<K, V, X extends Exception> implements ITransformerExn<K, V, X> {
37
 
38
    private final Map<K, V> map;
39
    private final boolean allowNullValue;
40
    private final ITransformerExn<K, V, X> function;
41
 
42
    public CachedTransformer(final Map<K, V> map, final ITransformerExn<K, V, X> function) {
43
        this(map, function, false);
44
    }
45
 
46
    public CachedTransformer(final Map<K, V> map, final ITransformerExn<K, V, X> function, final boolean allowNullValue) {
47
        this.map = map;
48
        this.function = function;
49
        this.allowNullValue = allowNullValue;
50
    }
51
 
52
    @Override
53
    public final V transformChecked(K key) throws X {
54
        return this.get(key);
55
    }
56
 
57
    public V get(K key) throws X {
58
        return CollectionUtils.computeIfAbsent(this.map, key, this.function, this.allowNullValue);
59
    }
60
}