001    /**
002     * Copyright (c) 2000-2010 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.util;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    
020    import java.lang.reflect.Method;
021    
022    /**
023     * @author Brian Wing Shun Chan
024     * @author Shuyang Zhou
025     */
026    public class InitialThreadLocal<T> extends ThreadLocal<T> {
027    
028            public InitialThreadLocal(String name, T initialValue) {
029                    _name = name;
030                    _initialValue = initialValue;
031    
032                    if (_initialValue instanceof Cloneable) {
033                            try {
034                                    _cloneMethod = _initialValue.getClass().getMethod(
035                                            _METHOD_CLONE);
036                            }
037                            catch (Exception e) {
038                                    _log.error(e, e);
039                            }
040                    }
041            }
042    
043            public String toString() {
044                    if (_name != null) {
045                            return _name;
046                    }
047                    else {
048                            return super.toString();
049                    }
050            }
051    
052            protected T initialValue() {
053                    if (_cloneMethod != null) {
054                            try {
055                                    return (T)_cloneMethod.invoke(_initialValue);
056                            }
057                            catch (Exception e) {
058                                    _log.error(e, e);
059                            }
060                    }
061    
062                    return _initialValue;
063            }
064    
065            private static final String _METHOD_CLONE = "clone";
066    
067            private static Log _log = LogFactoryUtil.getLog(InitialThreadLocal.class);
068    
069            private Method _cloneMethod;
070            private T _initialValue;
071            private String _name;
072    
073    }