01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.openejb.util;
17:
18: import java.util.concurrent.Callable;
19: import java.util.concurrent.ConcurrentHashMap;
20: import java.util.concurrent.ConcurrentMap;
21: import java.util.concurrent.ExecutionException;
22: import java.util.concurrent.Future;
23: import java.util.concurrent.FutureTask;
24:
25: public class Memoizer<K, V> implements Computable<K, V> {
26: private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
27:
28: private final Computable<K, V> c;
29:
30: public Memoizer(Computable<K, V> c) {
31: this .c = c;
32: }
33:
34: public V compute(final K key) throws InterruptedException {
35: while (true) {
36: Future<V> future = cache.get(key);
37: if (future == null) {
38:
39: Callable<V> eval = new Callable<V>() {
40: public V call() throws Exception {
41: return c.compute(key);
42: }
43: };
44: FutureTask<V> futureTask = new FutureTask<V>(eval);
45: future = cache.putIfAbsent(key, futureTask);
46: if (future == null) {
47: future = futureTask;
48: futureTask.run();
49: }
50: }
51: try {
52: return future.get();
53: } catch (ExecutionException e) {
54: e.printStackTrace();
55: }
56: }
57: }
58: }
|