1 package org.apidesign.javamonitorflaws;
3 import java.util.HashMap;
6 /** Classical caching support class that makes sure there is
7 * always one "To" value for each "From" one returned from the {@link #get}
8 * method. However it does not prevent multiple threads to call
9 * {@link #createItem} multiple times for the same "From" value.
13 * @author Jaroslav Tulach <jtulach@netbeans.org>
15 // BEGIN: monitor.pitfalls.Cache
16 public abstract class Cache<From,To> {
17 private Map<From,To> cache;
19 protected abstract To createItem(From f);
21 public final To get(From f) {
22 To t = inspectValue(f);
26 To newT = createItem(f);
27 return registerValue(f, newT);
31 private synchronized To inspectValue(From f) {
33 cache = new HashMap<From, To>();
38 private synchronized To registerValue(From f, To newT) {
48 // END: monitor.pitfalls.Cache