001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.util;
029
030import java.util.ArrayList;
031import java.util.List;
032
033/**
034 * Thread local stack.
035 *
036 * @param <T> the type for the stack elements
037 */
038public class CmsThreadLocalStack<T> {
039
040    /** The internal ThreadLocal storing the list. */
041    private ThreadLocal<List<T>> m_stackVar = ThreadLocal.withInitial(() -> new ArrayList<T>());
042
043    /**
044     * Removes and returns the last element pushed onto the stack.
045     *
046     * @return the last element pushed onto the stack
047     */
048    public T pop() {
049
050        return getStack().remove(getStack().size() - 1);
051    }
052
053    /**
054     * Pushes a new element onto the stack.
055     *
056     * @param data the element to push on the stack
057     */
058    public void push(T data) {
059
060        getStack().add(data);
061    }
062
063    /**
064     * Returns the current stack size.
065     *
066     * @return the current stack size
067     */
068    public int size() {
069
070        return getStack().size();
071    }
072
073    /**
074     * Returns the current top of the stack, without removing it.
075     * <p>
076     * If the stack is empty, null is returned.
077     *
078     * @return the current top of the stack
079     */
080    public T top() {
081
082        if (getStack().size() == 0) {
083            return null;
084        } else {
085            return getStack().get(getStack().size() - 1);
086        }
087    }
088
089    /**
090     * Gets the current list stored in the ThreadLocal.
091     *
092     * @return the current list stored in the ThreadLocal
093     */
094    private List<T> getStack() {
095
096        return m_stackVar.get();
097    }
098
099}