001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }