toothpick.ThreadSafeProviderImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of toothpick-runtime Show documentation
Show all versions of toothpick-runtime Show documentation
'Main Toothpick implementation'
package toothpick;
import java.lang.ref.WeakReference;
import javax.inject.Provider;
/**
* A thread safe internal provider. It will be exposed outside of Toothpick.
*
* @param the class of the instances provided by this provider.
*/
public class ThreadSafeProviderImpl implements Provider, Lazy {
private volatile T instance;
private WeakReference scope;
private Class clazz;
private String name;
private boolean isLazy;
public ThreadSafeProviderImpl(Scope scope, Class clazz, String name, boolean isLazy) {
this.scope = new WeakReference<>(scope);
this.clazz = clazz;
this.name = name;
this.isLazy = isLazy;
}
@Override
public T get() {
//the first test avoids accessing a volatile when not needed
if (isLazy && instance != null) {
return instance;
}
//ensure both sync for DSL
//and sync around provider
//so that dev's providers don't deal with concurrency
synchronized (this) {
if (isLazy) {
//DCL
if (instance == null) {
instance = getScope().getInstance(clazz, name);
scope.clear();
}
return instance;
}
return getScope().getInstance(clazz, name);
}
}
private Scope getScope() {
final Scope scope = this.scope.get();
if (scope == null) {
throw new IllegalStateException(String.format("The instance provided by the %s "
+ "cannot be created when the associated scope has been closed", isLazy ? "lazy" : "provider"));
}
return scope;
}
}