samples/deadlock/src/org/apidesign/javamonitorflaws/Cache.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 11 Feb 2009 08:52:00 +0100
changeset 317 e101649dbd17
parent 316 41a4abecb600
permissions -rw-r--r--
Marking code snippets for the "Java Monitor" wiki page
     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 // BEGIN: monitor.pitfalls.Cache
    16 public abstract class Cache<From,To> {
    17     private Map<From,To> cache;
    18 
    19     protected abstract To createItem(From f);
    20 
    21     public final To get(From f) {
    22         To t = inspectValue(f);
    23         if (t != null) {
    24             return t;
    25         }
    26         To newT = createItem(f);
    27         return registerValue(f, newT);
    28     }
    29 
    30 
    31     private synchronized To inspectValue(From f) {
    32         if (cache == null) {
    33             cache = new HashMap<From, To>();
    34         }
    35         return cache.get(f);
    36     }
    37 
    38     private synchronized To registerValue(From f, To newT) {
    39         To t = cache.get(f);
    40         if (t == null) {
    41             cache.put(f, newT);
    42             return newT;
    43         } else {
    44             return t;
    45         }
    46     }
    47 }
    48 // END: monitor.pitfalls.Cache