001    /**
002     * Copyright (c) 2000-2013 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.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            @Override
025            public T get() {
026                    SoftReference<T> softReference = _softReferenceThreadLocal.get();
027    
028                    if (softReference == _nullSoftReference) {
029                            return null;
030                    }
031    
032                    T value = null;
033    
034                    if (softReference != null) {
035                            value = softReference.get();
036                    }
037    
038                    if (value == null) {
039                            value = initialValue();
040    
041                            set(value);
042                    }
043    
044                    return value;
045            }
046    
047            @Override
048            public void remove() {
049                    _softReferenceThreadLocal.remove();
050            }
051    
052            @Override
053            public void set(T value) {
054                    if (value == null) {
055                            _softReferenceThreadLocal.set((SoftReference<T>)_nullSoftReference);
056                    }
057                    else {
058                            _softReferenceThreadLocal.set(new SoftReference<T>(value));
059                    }
060            }
061    
062            private static SoftReference<Object> _nullSoftReference =
063                    new SoftReference<Object>(null);
064    
065            private ThreadLocal<SoftReference<T>> _softReferenceThreadLocal =
066                    new ThreadLocal<SoftReference<T>>();
067    
068    }