All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.robolectric.util.SoftThreadLocal Maven / Gradle / Ivy

The newest version!
package org.robolectric.util;

import java.lang.ref.SoftReference;

/**
 * Soft reference to a {@code java.lang.ThreadLocal}.
 *
 * @param  The referent to track.
 */
public abstract class SoftThreadLocal {

  @SuppressWarnings({"AndroidJdkLibsChecker", "NewApi"})
  private final ThreadLocal> threadLocal =
      ThreadLocal.withInitial(() -> new SoftReference<>(create()));

  public synchronized T get() {
    T item = threadLocal.get().get();
    if (item == null) {
      item = create();
      threadLocal.set(new SoftReference<>(item));
    }
    return item;
  }

  public void set(T item) {
    threadLocal.set(new SoftReference<>(item));
  }

  protected abstract T create();
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy