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