001
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
026 public class InitialThreadLocal<T> extends CentralizedThreadLocal<T> {
027
028 public InitialThreadLocal(String name, T initialValue) {
029 this(name, initialValue, false);
030 }
031
032 public InitialThreadLocal(String name, T initialValue, boolean shortLived) {
033 super(shortLived);
034
035 _name = name;
036 _initialValue = initialValue;
037
038 if (_initialValue instanceof Cloneable) {
039 try {
040 _cloneMethod = _initialValue.getClass().getMethod(
041 _METHOD_CLONE);
042 }
043 catch (Exception e) {
044 _log.error(e, e);
045 }
046 }
047 }
048
049 @Override
050 public String toString() {
051 if (_name != null) {
052 return _name;
053 }
054 else {
055 return super.toString();
056 }
057 }
058
059 @Override
060 protected T initialValue() {
061 if (_cloneMethod != null) {
062 try {
063 return (T)_cloneMethod.invoke(_initialValue);
064 }
065 catch (Exception e) {
066 _log.error(e, e);
067 }
068 }
069
070 return _initialValue;
071 }
072
073 private static final String _METHOD_CLONE = "clone";
074
075 private static Log _log = LogFactoryUtil.getLog(InitialThreadLocal.class);
076
077 private Method _cloneMethod;
078 private T _initialValue;
079 private String _name;
080
081 }