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

jodd.petite.scope.ThreadLocalScope Maven / Gradle / Ivy

Go to download

Jodd Petite is slick and lightweight DI container that uses annotations and supports sufficient most of features offered by other containers.

There is a newer version: 6.0.2
Show newest version
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

package jodd.petite.scope;

import jodd.petite.BeanData;
import jodd.petite.BeanDefinition;

import java.util.HashMap;
import java.util.Map;

/**
 * Thread local Petite bean scope. Holds beans in thread local scopes.
 * Be careful with this scope, if you do not have control on threads!
 * For example, app servers may have a thread pools, so threads may not
 * finish when expected. ThreadLocalScope can not invoke destroy methods.
 */
public class ThreadLocalScope implements Scope {

	protected static ThreadLocal> context = new ThreadLocal>() {
		@Override
		protected synchronized Map initialValue() {
			return new HashMap();
		}
	};

	public Object lookup(String name) {
		Map threadLocalMap = context.get();
		BeanData beanData = threadLocalMap.get(name);
		if (beanData == null) {
			return null;
		}
		return beanData.getBean();
	}

	public void register(BeanDefinition beanDefinition, Object bean) {
		BeanData beanData = new BeanData(beanDefinition, bean);
		Map threadLocalMap = context.get();
		threadLocalMap.put(beanDefinition.getName(), beanData);
	}

	public void remove(String name) {
		Map threadLocalMap = context.get();
		threadLocalMap.remove(name);
	}

	/**
	 * Defines allowed referenced scopes that can be injected into the
	 * thread-local scoped bean.
	 */
	public boolean accept(Scope referenceScope) {
		Class refScopeType = referenceScope.getClass();

		if (refScopeType == SingletonScope.class) {
			return true;
		}

		if (refScopeType == ThreadLocalScope.class) {
			return true;
		}

		return false;
	}

	public void shutdown() {
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy