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

org.milyn.thread.StackedThreadLocal Maven / Gradle / Ivy

There is a newer version: 1.7.1
Show newest version
/*
	Milyn - Copyright (C) 2006 - 2010

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License (version 2.1) as published by the Free Software
	Foundation.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

	See the GNU Lesser General Public License for more details:
	http://www.gnu.org/licenses/lgpl.txt
*/
package org.milyn.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.EmptyStackException;
import java.util.Stack;

/**
 * Stacked ThreadLocal.
 * @author [email protected]
 */
public class StackedThreadLocal {

    private static Log logger = LogFactory.getLog(StackedThreadLocal.class);

    private String resourceName;
    private ThreadLocal> stackTL = new ThreadLocal>();

    public StackedThreadLocal(String resourceName) {
        this.resourceName = resourceName;
    }

    public T get() {
        Stack execContextStack = getExecutionContextStack();
        try {
            return execContextStack.peek();
        } catch (EmptyStackException e) {
            if(logger.isDebugEnabled()) {
                logger.debug("No currently stacked '" + resourceName + "' instance on active Thread.", e);
            }
            return null;
        }
    }

    public void set(T value) {
        Stack execContextStack = getExecutionContextStack();
        execContextStack.push(value);
    }

    public void remove() {
        Stack execContextStack = getExecutionContextStack();
        try {
            execContextStack.pop();
        } catch (EmptyStackException e) {
            if(logger.isDebugEnabled()) {
                logger.debug("No currently stacked '" + resourceName + "' instance on active Thread.", e);
            }
        }
    }

    private Stack getExecutionContextStack() {
        Stack stack = stackTL.get();
        if(stack == null) {
            synchronized (this) {
                stack = stackTL.get();
                if(stack == null) {
                    stack = new Stack();
                    stackTL.set(stack);
                }
            }
        }
        return stack;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy