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 Class<?> clazz = _initialValue.getClass();
041
042 _cloneMethod = clazz.getMethod(_METHOD_CLONE);
043 }
044 catch (Exception e) {
045 _log.error(e, e);
046 }
047 }
048 }
049
050 @Override
051 public String toString() {
052 if (_name != null) {
053 return _name;
054 }
055 else {
056 return super.toString();
057 }
058 }
059
060 @Override
061 protected T initialValue() {
062 if (_cloneMethod != null) {
063 try {
064 return (T)_cloneMethod.invoke(_initialValue);
065 }
066 catch (Exception e) {
067 _log.error(e, e);
068 }
069 }
070
071 return _initialValue;
072 }
073
074 private static final String _METHOD_CLONE = "clone";
075
076 private static Log _log = LogFactoryUtil.getLog(InitialThreadLocal.class);
077
078 private Method _cloneMethod;
079 private T _initialValue;
080 private String _name;
081
082 }