emul/src/main/java/java/lang/ClassValue.java
branchjdk7-b147
changeset 1981 189dcebe46c6
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/emul/src/main/java/java/lang/ClassValue.java	Tue Jan 17 06:11:57 2017 +0100
     1.3 @@ -0,0 +1,239 @@
     1.4 +/*
     1.5 + * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.lang;
    1.30 +
    1.31 +import java.util.WeakHashMap;
    1.32 +import java.util.concurrent.atomic.AtomicInteger;
    1.33 +
    1.34 +/**
    1.35 + * Lazily associate a computed value with (potentially) every type.
    1.36 + * For example, if a dynamic language needs to construct a message dispatch
    1.37 + * table for each class encountered at a message send call site,
    1.38 + * it can use a {@code ClassValue} to cache information needed to
    1.39 + * perform the message send quickly, for each class encountered.
    1.40 + * @author John Rose, JSR 292 EG
    1.41 + * @since 1.7
    1.42 + */
    1.43 +public abstract class ClassValue<T> {
    1.44 +    /**
    1.45 +     * Sole constructor.  (For invocation by subclass constructors, typically
    1.46 +     * implicit.)
    1.47 +     */
    1.48 +    protected ClassValue() {
    1.49 +    }
    1.50 +
    1.51 +    /**
    1.52 +     * Computes the given class's derived value for this {@code ClassValue}.
    1.53 +     * <p>
    1.54 +     * This method will be invoked within the first thread that accesses
    1.55 +     * the value with the {@link #get get} method.
    1.56 +     * <p>
    1.57 +     * Normally, this method is invoked at most once per class,
    1.58 +     * but it may be invoked again if there has been a call to
    1.59 +     * {@link #remove remove}.
    1.60 +     * <p>
    1.61 +     * If this method throws an exception, the corresponding call to {@code get}
    1.62 +     * will terminate abnormally with that exception, and no class value will be recorded.
    1.63 +     *
    1.64 +     * @param type the type whose class value must be computed
    1.65 +     * @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
    1.66 +     * @see #get
    1.67 +     * @see #remove
    1.68 +     */
    1.69 +    protected abstract T computeValue(Class<?> type);
    1.70 +
    1.71 +    /**
    1.72 +     * Returns the value for the given class.
    1.73 +     * If no value has yet been computed, it is obtained by
    1.74 +     * an invocation of the {@link #computeValue computeValue} method.
    1.75 +     * <p>
    1.76 +     * The actual installation of the value on the class
    1.77 +     * is performed atomically.
    1.78 +     * At that point, if several racing threads have
    1.79 +     * computed values, one is chosen, and returned to
    1.80 +     * all the racing threads.
    1.81 +     * <p>
    1.82 +     * The {@code type} parameter is typically a class, but it may be any type,
    1.83 +     * such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
    1.84 +     * <p>
    1.85 +     * In the absence of {@code remove} calls, a class value has a simple
    1.86 +     * state diagram:  uninitialized and initialized.
    1.87 +     * When {@code remove} calls are made,
    1.88 +     * the rules for value observation are more complex.
    1.89 +     * See the documentation for {@link #remove remove} for more information.
    1.90 +     *
    1.91 +     * @param type the type whose class value must be computed or retrieved
    1.92 +     * @return the current value associated with this {@code ClassValue}, for the given class or interface
    1.93 +     * @throws NullPointerException if the argument is null
    1.94 +     * @see #remove
    1.95 +     * @see #computeValue
    1.96 +     */
    1.97 +    public T get(Class<?> type) {
    1.98 +        ClassValueMap map = getMap(type);
    1.99 +        if (map != null) {
   1.100 +            Object x = map.get(this);
   1.101 +            if (x != null) {
   1.102 +                return (T) map.unmaskNull(x);
   1.103 +            }
   1.104 +        }
   1.105 +        return setComputedValue(type);
   1.106 +    }
   1.107 +
   1.108 +    /**
   1.109 +     * Removes the associated value for the given class.
   1.110 +     * If this value is subsequently {@linkplain #get read} for the same class,
   1.111 +     * its value will be reinitialized by invoking its {@link #computeValue computeValue} method.
   1.112 +     * This may result in an additional invocation of the
   1.113 +     * {@code computeValue} method for the given class.
   1.114 +     * <p>
   1.115 +     * In order to explain the interaction between {@code get} and {@code remove} calls,
   1.116 +     * we must model the state transitions of a class value to take into account
   1.117 +     * the alternation between uninitialized and initialized states.
   1.118 +     * To do this, number these states sequentially from zero, and note that
   1.119 +     * uninitialized (or removed) states are numbered with even numbers,
   1.120 +     * while initialized (or re-initialized) states have odd numbers.
   1.121 +     * <p>
   1.122 +     * When a thread {@code T} removes a class value in state {@code 2N},
   1.123 +     * nothing happens, since the class value is already uninitialized.
   1.124 +     * Otherwise, the state is advanced atomically to {@code 2N+1}.
   1.125 +     * <p>
   1.126 +     * When a thread {@code T} queries a class value in state {@code 2N},
   1.127 +     * the thread first attempts to initialize the class value to state {@code 2N+1}
   1.128 +     * by invoking {@code computeValue} and installing the resulting value.
   1.129 +     * <p>
   1.130 +     * When {@code T} attempts to install the newly computed value,
   1.131 +     * if the state is still at {@code 2N}, the class value will be initialized
   1.132 +     * with the computed value, advancing it to state {@code 2N+1}.
   1.133 +     * <p>
   1.134 +     * Otherwise, whether the new state is even or odd,
   1.135 +     * {@code T} will discard the newly computed value
   1.136 +     * and retry the {@code get} operation.
   1.137 +     * <p>
   1.138 +     * Discarding and retrying is an important proviso,
   1.139 +     * since otherwise {@code T} could potentially install
   1.140 +     * a disastrously stale value.  For example:
   1.141 +     * <ul>
   1.142 +     * <li>{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
   1.143 +     * <li>{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
   1.144 +     * <li>{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
   1.145 +     * <li>...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
   1.146 +     * <li>{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
   1.147 +     * <li>{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
   1.148 +     * <li> the previous actions of {@code T2} are repeated several times
   1.149 +     * <li> also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
   1.150 +     * <li>...meanwhile, {@code T} wakes up and attempts to install {@code V0}; <em>this must fail</em>
   1.151 +     * </ul>
   1.152 +     * We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
   1.153 +     * observe the time-dependent states as it computes {@code V1}, etc.
   1.154 +     * This does not remove the threat of a stale value, since there is a window of time
   1.155 +     * between the return of {@code computeValue} in {@code T} and the installation
   1.156 +     * of the the new value.  No user synchronization is possible during this time.
   1.157 +     *
   1.158 +     * @param type the type whose class value must be removed
   1.159 +     * @throws NullPointerException if the argument is null
   1.160 +     */
   1.161 +    public void remove(Class<?> type) {
   1.162 +        ClassValueMap map = getMap(type);
   1.163 +        if (map != null) {
   1.164 +            synchronized (map) {
   1.165 +                map.remove(this);
   1.166 +            }
   1.167 +        }
   1.168 +    }
   1.169 +
   1.170 +    /// Implementation...
   1.171 +    // FIXME: Use a data structure here similar that of ThreadLocal (7030453).
   1.172 +
   1.173 +    private static final AtomicInteger STORE_BARRIER = new AtomicInteger();
   1.174 +
   1.175 +    /** Slow path for {@link #get}. */
   1.176 +    private T setComputedValue(Class<?> type) {
   1.177 +        ClassValueMap map = getMap(type);
   1.178 +        if (map == null) {
   1.179 +            map = initializeMap(type);
   1.180 +        }
   1.181 +        T value = computeValue(type);
   1.182 +        STORE_BARRIER.lazySet(0);
   1.183 +        // All stores pending from computeValue are completed.
   1.184 +        synchronized (map) {
   1.185 +            // Warm up the table with a null entry.
   1.186 +            map.preInitializeEntry(this);
   1.187 +        }
   1.188 +        STORE_BARRIER.lazySet(0);
   1.189 +        // All stores pending from table expansion are completed.
   1.190 +        synchronized (map) {
   1.191 +            value = (T) map.initializeEntry(this, value);
   1.192 +            // One might fear a possible race condition here
   1.193 +            // if the code for map.put has flushed the write
   1.194 +            // to map.table[*] before the writes to the Map.Entry
   1.195 +            // are done.  This is not possible, since we have
   1.196 +            // warmed up the table with an empty entry.
   1.197 +        }
   1.198 +        return value;
   1.199 +    }
   1.200 +
   1.201 +    // Replace this map by a per-class slot.
   1.202 +    private static final WeakHashMap<Class<?>, ClassValueMap> ROOT
   1.203 +        = new WeakHashMap<Class<?>, ClassValueMap>();
   1.204 +
   1.205 +    private static ClassValueMap getMap(Class<?> type) {
   1.206 +        type.getClass();  // test for null
   1.207 +        return ROOT.get(type);
   1.208 +    }
   1.209 +
   1.210 +    private static ClassValueMap initializeMap(Class<?> type) {
   1.211 +        synchronized (ClassValue.class) {
   1.212 +            ClassValueMap map = ROOT.get(type);
   1.213 +            if (map == null)
   1.214 +                ROOT.put(type, map = new ClassValueMap());
   1.215 +            return map;
   1.216 +        }
   1.217 +    }
   1.218 +
   1.219 +    static class ClassValueMap extends WeakHashMap<ClassValue, Object> {
   1.220 +        /** Make sure this table contains an Entry for the given key, even if it is empty. */
   1.221 +        void preInitializeEntry(ClassValue key) {
   1.222 +            if (!this.containsKey(key))
   1.223 +                this.put(key, null);
   1.224 +        }
   1.225 +        /** Make sure this table contains a non-empty Entry for the given key. */
   1.226 +        Object initializeEntry(ClassValue key, Object value) {
   1.227 +            Object prior = this.get(key);
   1.228 +            if (prior != null) {
   1.229 +                return unmaskNull(prior);
   1.230 +            }
   1.231 +            this.put(key, maskNull(value));
   1.232 +            return value;
   1.233 +        }
   1.234 +
   1.235 +        Object maskNull(Object x) {
   1.236 +            return x == null ? this : x;
   1.237 +        }
   1.238 +        Object unmaskNull(Object x) {
   1.239 +            return x == this ? null : x;
   1.240 +        }
   1.241 +    }
   1.242 +}