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.memory;
016    
017    import java.lang.ref.SoftReference;
018    
019    /**
020     * @author Shuyang Zhou
021     */
022    public class SoftReferenceThreadLocal<T> extends ThreadLocal<T> {
023    
024            public T get() {
025                    SoftReference<T> softReference = _softReferenceThreadLocal.get();
026    
027                    if (softReference == _nullSoftReference) {
028                            return null;
029                    }
030    
031                    T value = null;
032    
033                    if (softReference != null) {
034                            value = softReference.get();
035                    }
036    
037                    if (value == null) {
038                            value = initialValue();
039    
040                            set(value);
041                    }
042    
043                    return value;
044            }
045    
046            public void remove() {
047                    _softReferenceThreadLocal.remove();
048            }
049    
050            public void set(T value) {
051                    if (value == null) {
052                            _softReferenceThreadLocal.set((SoftReference<T>)_nullSoftReference);
053                    }
054                    else {
055                            _softReferenceThreadLocal.set(new SoftReference<T>(value));
056                    }
057            }
058    
059            private static SoftReference<Object> _nullSoftReference =
060                    new SoftReference<Object>(null);
061    
062            private ThreadLocal<SoftReference<T>> _softReferenceThreadLocal =
063                    new ThreadLocal<SoftReference<T>>();
064    
065    }