• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.robolectric.util;
2 
3 import java.lang.ref.SoftReference;
4 
5 /**
6  * Soft reference to a {@code java.lang.ThreadLocal}.
7  *
8  * @param <T> The referent to track.
9  */
10 public abstract class SoftThreadLocal<T> {
11 
12   private final ThreadLocal<SoftReference<T>> threadLocal = new ThreadLocal<SoftReference<T>>() {
13     @Override protected SoftReference<T> initialValue() {
14       return new SoftReference<>(create());
15     }
16   };
17 
get()18   synchronized public T get() {
19     T item = threadLocal.get().get();
20     if (item == null) {
21       item = create();
22       threadLocal.set(new SoftReference<>(item));
23     }
24     return item;
25   }
26 
set(T item)27   public void set(T item) {
28     threadLocal.set(new SoftReference<>(item));
29   }
30 
create()31   abstract protected T create();
32 }
33