1 /* 2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 package java.lang.reflect; 25 26 import jdk.internal.loader.BootLoader; 27 import jdk.internal.misc.JavaLangAccess; 28 import jdk.internal.misc.SharedSecrets; 29 30 import java.util.Iterator; 31 import java.util.Objects; 32 import java.util.concurrent.ConcurrentHashMap; 33 import java.util.function.BiFunction; 34 import java.util.function.Supplier; 35 36 /** 37 * AbstractClassLoaderValue is a superclass of root-{@link ClassLoaderValue} 38 * and {@link Sub sub}-ClassLoaderValue. 39 * 40 * @param <CLV> the type of concrete ClassLoaderValue (this type) 41 * @param <V> the type of values associated with ClassLoaderValue 42 */ 43 abstract class AbstractClassLoaderValue<CLV extends AbstractClassLoaderValue<CLV, V>, V> { 44 45 /** 46 * Sole constructor. 47 */ 48 AbstractClassLoaderValue() {} 49 50 /** 51 * Returns the key component of this ClassLoaderValue. The key component of 52 * the root-{@link ClassLoaderValue} is the ClassLoaderValue itself, 53 * while the key component of a {@link #sub(Object) sub}-ClassLoaderValue 54 * is what was given to construct it. 55 * 56 * @return the key component of this ClassLoaderValue. 57 */ 58 public abstract Object key(); 59 60 /** 61 * Constructs new sub-ClassLoaderValue of this ClassLoaderValue with given 62 * key component. 63 * 64 * @param key the key component of the sub-ClassLoaderValue. 65 * @param <K> the type of the key component. 66 * @return a sub-ClassLoaderValue of this ClassLoaderValue for given key 67 */ 68 public <K> Sub<K> sub(K key) { 69 return new Sub<>(key); 70 } 71 72 /** 73 * Returns {@code true} if this ClassLoaderValue is equal to given {@code clv} 74 * or if this ClassLoaderValue was derived from given {@code clv} by a chain 75 * of {@link #sub(Object)} invocations. 76 * 77 * @param clv the ClassLoaderValue to test this against 78 * @return if this ClassLoaderValue is equal to given {@code clv} or 79 * its descendant 80 */ 81 public abstract boolean isEqualOrDescendantOf(AbstractClassLoaderValue<?, V> clv); 82 83 /** 84 * Returns the value associated with this ClassLoaderValue and given ClassLoader 85 * or {@code null} if there is none. 86 * 87 * @param cl the ClassLoader for the associated value 88 * @return the value associated with this ClassLoaderValue and given ClassLoader 89 * or {@code null} if there is none. 90 */ 91 public V get(ClassLoader cl) { 92 Object val = AbstractClassLoaderValue.<CLV>map(cl).get(this); 93 try { 94 return extractValue(val); 95 } catch (Memoizer.RecursiveInvocationException e) { 96 // propagate recursive get() for the same key that is just 97 // being calculated in computeIfAbsent() 98 throw e; 99 } catch (Throwable t) { 100 // don't propagate exceptions thrown from Memoizer - pretend 101 // that there was no entry 102 // (computeIfAbsent invocation will try to remove it anyway) 103 return null; 104 } 105 } 106 107 /** 108 * Associates given value {@code v} with this ClassLoaderValue and given 109 * ClassLoader and returns {@code null} if there was no previously associated 110 * value or does nothing and returns previously associated value if there 111 * was one. 112 * 113 * @param cl the ClassLoader for the associated value 114 * @param v the value to associate 115 * @return previously associated value or null if there was none 116 */ 117 public V putIfAbsent(ClassLoader cl, V v) { 118 ConcurrentHashMap<CLV, Object> map = map(cl); 119 @SuppressWarnings("unchecked") 120 CLV clv = (CLV) this; 121 while (true) { 122 try { 123 Object val = map.putIfAbsent(clv, v); 124 return extractValue(val); 125 } catch (Memoizer.RecursiveInvocationException e) { 126 // propagate RecursiveInvocationException for the same key that 127 // is just being calculated in computeIfAbsent 128 throw e; 129 } catch (Throwable t) { 130 // don't propagate exceptions thrown from foreign Memoizer - 131 // pretend that there was no entry and retry 132 // (foreign computeIfAbsent invocation will try to remove it anyway) 133 } 134 // TODO: 135 // Thread.onSpinLoop(); // when available 136 } 137 } 138 139 /** 140 * Removes the value associated with this ClassLoaderValue and given 141 * ClassLoader if the associated value is equal to given value {@code v} and 142 * returns {@code true} or does nothing and returns {@code false} if there is 143 * no currently associated value or it is not equal to given value {@code v}. 144 * 145 * @param cl the ClassLoader for the associated value 146 * @param v the value to compare with currently associated value 147 * @return {@code true} if the association was removed or {@code false} if not 148 */ 149 public boolean remove(ClassLoader cl, Object v) { 150 return AbstractClassLoaderValue.<CLV>map(cl).remove(this, v); 151 } 152 153 /** 154 * Returns the value associated with this ClassLoaderValue and given 155 * ClassLoader if there is one or computes the value by invoking given 156 * {@code mappingFunction}, associates it and returns it. 157 * <p> 158 * Computation and association of the computed value is performed atomically 159 * by the 1st thread that requests a particular association while holding a 160 * lock associated with this ClassLoaderValue and given ClassLoader. 161 * Nested calls from the {@code mappingFunction} to {@link #get}, 162 * {@link #putIfAbsent} or {@link #computeIfAbsent} for the same association 163 * are not allowed and throw {@link IllegalStateException}. Nested call to 164 * {@link #remove} for the same association is allowed but will always return 165 * {@code false} regardless of passed-in comparison value. Nested calls for 166 * other association(s) are allowed, but care should be taken to avoid 167 * deadlocks. When two threads perform nested computations of the overlapping 168 * set of associations they should always request them in the same order. 169 * 170 * @param cl the ClassLoader for the associated value 171 * @param mappingFunction the function to compute the value 172 * @return the value associated with given ClassLoader and key components. 173 * @throws IllegalStateException if a direct or indirect invocation from 174 * within given {@code mappingFunction} that 175 * computes the value of a particular association 176 * to {@link #get}, {@link #putIfAbsent} or 177 * {@link #computeIfAbsent} 178 * for the same association is attempted. 179 */ 180 public V computeIfAbsent(ClassLoader cl, 181 BiFunction< 182 ? super ClassLoader, 183 ? super CLV, 184 ? extends V 185 > mappingFunction) throws IllegalStateException { 186 ConcurrentHashMap<CLV, Object> map = map(cl); 187 @SuppressWarnings("unchecked") 188 CLV clv = (CLV) this; 189 Memoizer<CLV, V> mv = null; 190 while (true) { 191 Object val = (mv == null) ? map.get(clv) : map.putIfAbsent(clv, mv); 192 if (val == null) { 193 if (mv == null) { 194 // create Memoizer lazily when 1st needed and restart loop 195 mv = new Memoizer<>(cl, clv, mappingFunction); 196 continue; 197 } 198 // mv != null, therefore sv == null was a result of successful 199 // putIfAbsent 200 try { 201 // trigger Memoizer to compute the value 202 V v = mv.get(); 203 // attempt to replace our Memoizer with the value 204 map.replace(clv, mv, v); 205 // return computed value 206 return v; 207 } catch (Throwable t) { 208 // our Memoizer has thrown, attempt to remove it 209 map.remove(clv, mv); 210 // propagate exception because it's from our Memoizer 211 throw t; 212 } 213 } else { 214 try { 215 return extractValue(val); 216 } catch (Memoizer.RecursiveInvocationException e) { 217 // propagate recursive attempts to calculate the same 218 // value as being calculated at the moment 219 throw e; 220 } catch (Throwable t) { 221 // don't propagate exceptions thrown from foreign Memoizer - 222 // pretend that there was no entry and retry 223 // (foreign computeIfAbsent invocation will try to remove it anyway) 224 } 225 } 226 // TODO: 227 // Thread.onSpinLoop(); // when available 228 } 229 } 230 231 /** 232 * Removes all values associated with given ClassLoader {@code cl} and 233 * {@link #isEqualOrDescendantOf(AbstractClassLoaderValue) this or descendants} 234 * of this ClassLoaderValue. 235 * This is not an atomic operation. Other threads may see some associations 236 * be already removed and others still present while this method is executing. 237 * <p> 238 * The sole intention of this method is to cleanup after a unit test that 239 * tests ClassLoaderValue directly. It is not intended for use in 240 * actual algorithms. 241 * 242 * @param cl the associated ClassLoader of the values to be removed 243 */ 244 public void removeAll(ClassLoader cl) { 245 ConcurrentHashMap<CLV, Object> map = map(cl); 246 for (Iterator<CLV> i = map.keySet().iterator(); i.hasNext(); ) { 247 if (i.next().isEqualOrDescendantOf(this)) { 248 i.remove(); 249 } 250 } 251 } 252 253 private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); 254 255 /** 256 * @return a ConcurrentHashMap for given ClassLoader 257 */ 258 @SuppressWarnings("unchecked") 259 private static <CLV extends AbstractClassLoaderValue<CLV, ?>> 260 ConcurrentHashMap<CLV, Object> map(ClassLoader cl) { 261 return (ConcurrentHashMap<CLV, Object>) 262 (cl == null 263 ? BootLoader.getClassLoaderValueMap() 264 : JLA.createOrGetClassLoaderValueMap(cl) 265 ); 266 } 267 268 /** 269 * @return value extracted from the {@link Memoizer} if given 270 * {@code memoizerOrValue} parameter is a {@code Memoizer} or 271 * just return given parameter. 272 */ 273 @SuppressWarnings("unchecked") 274 private V extractValue(Object memoizerOrValue) { 275 if (memoizerOrValue instanceof Memoizer) { 276 return ((Memoizer<?, V>) memoizerOrValue).get(); 277 } else { 278 return (V) memoizerOrValue; 279 } 280 } 281 282 /** 283 * A memorizing supplier that invokes given {@code mappingFunction} just once 284 * and then returns memorized result or throws memorized exception. 285 * If given mappingFunction returns null, it is converted to NullPointerException, 286 * thrown from the Memoizer's {@link #get()} method and memorized. 287 * If the Memoizer is invoked recursively from the given {@code mappingFunction}, 288 * {@link RecursiveInvocationException} is thrown, but not memorized. 289 * The in-flight call to the {@link #get()} can still complete successfully if 290 * such exception is handled by the mappingFunction. 291 */ 292 private static final class Memoizer<CLV extends AbstractClassLoaderValue<CLV, V>, V> 293 implements Supplier<V> { 294 295 private final ClassLoader cl; 296 private final CLV clv; 297 private final BiFunction<? super ClassLoader, ? super CLV, ? extends V> 298 mappingFunction; 299 300 private volatile V v; 301 private volatile Throwable t; 302 private boolean inCall; 303 304 Memoizer(ClassLoader cl, 305 CLV clv, 306 BiFunction<? super ClassLoader, ? super CLV, ? extends V> 307 mappingFunction 308 ) { 309 this.cl = cl; 310 this.clv = clv; 311 this.mappingFunction = mappingFunction; 312 } 313 314 @Override 315 public V get() throws RecursiveInvocationException { 316 V v = this.v; 317 if (v != null) return v; 318 Throwable t = this.t; 319 if (t == null) { 320 synchronized (this) { 321 if ((v = this.v) == null && (t = this.t) == null) { 322 if (inCall) { 323 throw new RecursiveInvocationException(); 324 } 325 inCall = true; 326 try { 327 this.v = v = Objects.requireNonNull( 328 mappingFunction.apply(cl, clv)); 329 } catch (Throwable x) { 330 this.t = t = x; 331 } finally { 332 inCall = false; 333 } 334 } 335 } 336 } 337 if (v != null) return v; 338 if (t instanceof Error) { 339 throw (Error) t; 340 } else if (t instanceof RuntimeException) { 341 throw (RuntimeException) t; 342 } else { 343 throw new UndeclaredThrowableException(t); 344 } 345 } 346 347 static class RecursiveInvocationException extends IllegalStateException { 348 private static final long serialVersionUID = 1L; 349 350 RecursiveInvocationException() { 351 super("Recursive call"); 352 } 353 } 354 } 355 356 /** 357 * sub-ClassLoaderValue is an inner class of {@link AbstractClassLoaderValue} 358 * and also a subclass of it. It can therefore be instantiated as an inner 359 * class of either an instance of root-{@link ClassLoaderValue} or another 360 * instance of itself. This enables composing type-safe compound keys of 361 * arbitrary length: 362 * <pre>{@code 363 * ClassLoaderValue<V> clv = new ClassLoaderValue<>(); 364 * ClassLoaderValue<V>.Sub<K1>.Sub<K2>.Sub<K3> clv_k123 = 365 * clv.sub(k1).sub(k2).sub(k3); 366 * }</pre> 367 * From which individual components are accessible in a type-safe way: 368 * <pre>{@code 369 * K1 k1 = clv_k123.parent().parent().key(); 370 * K2 k2 = clv_k123.parent().key(); 371 * K3 k3 = clv_k123.key(); 372 * }</pre> 373 * This allows specifying non-capturing lambdas for the mapping function of 374 * {@link #computeIfAbsent(ClassLoader, BiFunction)} operation that can 375 * access individual key components from passed-in 376 * sub-[sub-...]ClassLoaderValue instance in a type-safe way. 377 * 378 * @param <K> the type of {@link #key()} component contained in the 379 * sub-ClassLoaderValue. 380 */ 381 final class Sub<K> extends AbstractClassLoaderValue<Sub<K>, V> { 382 383 private final K key; 384 385 Sub(K key) { 386 this.key = key; 387 } 388 389 /** 390 * @return the parent ClassLoaderValue this sub-ClassLoaderValue 391 * has been {@link #sub(Object) derived} from. 392 */ 393 public AbstractClassLoaderValue<CLV, V> parent() { 394 return AbstractClassLoaderValue.this; 395 } 396 397 /** 398 * @return the key component of this sub-ClassLoaderValue. 399 */ 400 @Override 401 public K key() { 402 return key; 403 } 404 405 /** 406 * sub-ClassLoaderValue is a descendant of given {@code clv} if it is 407 * either equal to it or if its {@link #parent() parent} is a 408 * descendant of given {@code clv}. 409 */ 410 @Override 411 public boolean isEqualOrDescendantOf(AbstractClassLoaderValue<?, V> clv) { 412 return equals(Objects.requireNonNull(clv)) || 413 parent().isEqualOrDescendantOf(clv); 414 } 415 416 @Override 417 public boolean equals(Object o) { 418 if (this == o) return true; 419 if (!(o instanceof Sub)) return false; 420 @SuppressWarnings("unchecked") 421 Sub<?> that = (Sub<?>) o; 422 return this.parent().equals(that.parent()) && 423 Objects.equals(this.key, that.key); 424 } 425 426 @Override 427 public int hashCode() { 428 return 31 * parent().hashCode() + 429 Objects.hashCode(key); 430 } 431 } 432 }