samples/deadlock/src/org/apidesign/javamonitorflaws/Cache.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 11 Feb 2009 07:12:41 +0100
changeset 316 41a4abecb600
parent 315 08dd52950883
child 317 e101649dbd17
permissions -rw-r--r--
Rewritten to rely on (private) synchronized methods
     1 package org.apidesign.javamonitorflaws;
     2 
     3 import java.util.HashMap;
     4 import java.util.Map;
     5 
     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.
    10  * <p>
    11  *
    12  *
    13  * @author Jaroslav Tulach <jtulach@netbeans.org>
    14  */
    15 public abstract class Cache<From,To> {
    16     private Map<From,To> cache;
    17 
    18     protected abstract To createItem(From f);
    19 
    20     public final To get(From f) {
    21         To t = inspectValue(f);
    22         if (t != null) {
    23             return t;
    24         }
    25         To newT = createItem(f);
    26         return registerValue(f, newT);
    27     }
    28 
    29 
    30     private synchronized To inspectValue(From f) {
    31         if (cache == null) {
    32             cache = new HashMap<From, To>();
    33         }
    34         return cache.get(f);
    35     }
    36 
    37     private synchronized To registerValue(From f, To newT) {
    38         To t = cache.get(f);
    39         if (t == null) {
    40             cache.put(f, newT);
    41             return newT;
    42         } else {
    43             return t;
    44         }
    45     }
    46 }