samples/deadlock/src/org/apidesign/javamonitorflaws/CacheOK.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 319 6c1d8b5553d8
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     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  * In contrast to {@link Cache}, this is correctly synchronized.
    12  *
    13  * @author Jaroslav Tulach <jtulach@netbeans.org>
    14  */
    15 // BEGIN: monitor.pitfalls.CacheOK
    16 public abstract class CacheOK<From,To> {
    17     private final Object LOCK = new Object();
    18 
    19     private Map<From,To> cache;
    20 
    21     protected abstract To createItem(From f);
    22 
    23     public final To get(From f) {
    24         To t = inspectValue(f);
    25         if (t != null) {
    26             return t;
    27         }
    28         To newT = createItem(f);
    29         return registerValue(f, newT);
    30     }
    31 
    32 
    33     private To inspectValue(From f) {
    34         synchronized (LOCK) {
    35             if (cache == null) {
    36                 cache = new HashMap<From, To>();
    37             }
    38             return cache.get(f);
    39         }
    40     }
    41 
    42     private To registerValue(From f, To newT) {
    43         synchronized (LOCK) {
    44             To t = cache.get(f);
    45             if (t == null) {
    46                 cache.put(f, newT);
    47                 return newT;
    48             } else {
    49                 return t;
    50             }
    51         }
    52     }
    53 }
    54 // END: monitor.pitfalls.CacheOK