01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.aspectwerkz.util;
05:
06: import java.io.Serializable;
07: import java.lang.ref.WeakReference;
08:
09: /**
10: * Extends the <code>java.lang.ThreadLocal</code> to be able to add additional functionality. <p/>This classes
11: * enhances the base implementation by: <p/>making it serializable <p/>making it wrap an unwrap the values in a
12: * <code>java.lang.ref.WeakReference</code> to avoid potential memory leaks
13: *
14: * @author <a href="mailto:jboner@codehaus.org">Jonas BonŽr </a>
15: */
16: public class SerializableThreadLocal extends java.lang.ThreadLocal
17: implements Serializable {
18: /**
19: * Constructor. Simply calls the base class constructor.
20: */
21: public SerializableThreadLocal() {
22: super ();
23: }
24:
25: /**
26: * Overrides the <code>java.lang.ThreadLocal#getDefault()</code> method. Retrieves and returns the value wrapped up in a
27: * <code>java.lang.ref.WeakReference</code> by the <code>SerializableThreadLocal#set(Object value)</code> method
28: *
29: * @return the value wrapped up in a weak reference
30: */
31: public Object get() {
32: Object ref = super .get();
33: if (ref == null) {
34: return ref;
35: } else {
36: return ((WeakReference) ref).get();
37: }
38: }
39:
40: /**
41: * Overrides the <code>java.lang.ThreadLoca#set(Object value)</code> method. Wraps the value in a
42: * <code>java.lang.ref.WeakReference</code> before passing it on to the <code>java.lang.ThreadLocal#set(Object
43: * value)</code>
44: * method
45: *
46: * @param value the value that should be wrapped up in a weak reference
47: */
48: public void set(final Object value) {
49: synchronized (this ) {
50: super .set(new WeakReference(value));
51: }
52: }
53: }
|