| SoftReferenceThreadLocal.java |
1 /**
2 * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3 *
4 * The contents of this file are subject to the terms of the Liferay Enterprise
5 * Subscription License ("License"). You may not use this file except in
6 * compliance with the License. You can obtain a copy of the License by
7 * contacting Liferay, Inc. See the License for the specific language governing
8 * permissions and limitations under the License, including but not limited to
9 * distribution rights of the Software.
10 *
11 *
12 *
13 */
14
15 package com.liferay.portal.kernel.memory;
16
17 import java.lang.ref.SoftReference;
18
19 /**
20 * <a href="SoftReferenceThreadLocal.java.html"><b><i>View Source</i></b></a>
21 *
22 * @author Shuyang Zhou
23 */
24 public class SoftReferenceThreadLocal<T> extends ThreadLocal<T> {
25
26 public T get() {
27 SoftReference<T> softReference = _softReferenceThreadLocal.get();
28
29 if (softReference == _nullSoftReference) {
30 return null;
31 }
32
33 T value = null;
34
35 if (softReference != null) {
36 value = softReference.get();
37 }
38
39 if (value == null) {
40 value = initialValue();
41
42 set(value);
43 }
44
45 return value;
46 }
47
48 public void remove() {
49 _softReferenceThreadLocal.remove();
50 }
51
52 public void set(T value) {
53 if (value == null) {
54 _softReferenceThreadLocal.set((SoftReference<T>)_nullSoftReference);
55 }
56 else {
57 _softReferenceThreadLocal.set(new SoftReference<T>(value));
58 }
59 }
60
61 private static SoftReference<Object> _nullSoftReference =
62 new SoftReference<Object>(null);
63
64 private ThreadLocal<SoftReference<T>> _softReferenceThreadLocal =
65 new ThreadLocal<SoftReference<T>>();
66
67 }