001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.cache;
016    
017    import com.liferay.portal.kernel.util.StringBundler;
018    
019    import java.util.HashMap;
020    import java.util.Map;
021    
022    /**
023     * @author Shuyang Zhou
024     */
025    public class ThreadLocalCache<T> {
026    
027            public ThreadLocalCache(String name, Lifecycle lifecycle) {
028                    _name = name;
029                    _lifecycle = lifecycle;
030            }
031    
032            public T get(String key) {
033                    if (_cache == null) {
034                            return null;
035                    }
036                    else {
037                            return _cache.get(key);
038                    }
039            }
040    
041            public Lifecycle getLifecycle() {
042                    return _lifecycle;
043            }
044    
045            public String getName() {
046                    return _name;
047            }
048    
049            public void put(String key, T obj) {
050                    if (_cache == null) {
051                            _cache = new HashMap<String, T>();
052                    }
053    
054                    _cache.put(key, obj);
055            }
056    
057            public void remove(String key) {
058                    if (_cache != null) {
059                            _cache.remove(key);
060                    }
061            }
062    
063            public void removeAll() {
064                    if (_cache != null) {
065                            _cache.clear();
066                    }
067            }
068    
069            public String toString() {
070                    StringBundler sb = new StringBundler(7);
071    
072                    sb.append("{cache=");
073                    sb.append(_cache.toString());
074                    sb.append(", lifecycle=");
075                    sb.append(_lifecycle);
076                    sb.append(", name=");
077                    sb.append(_name);
078                    sb.append("}");
079    
080                    return sb.toString();
081            }
082    
083            private Map<String, T> _cache;
084            private Lifecycle _lifecycle;
085            private String _name;
086    
087    }