KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > codehaus > aspectwerkz > util > SerializableThreadLocal


1 /**************************************************************************************
2  * Copyright (c) Jonas BonŽr, Alexandre Vasseur. All rights reserved. *
3  * http://aspectwerkz.codehaus.org *
4  * ---------------------------------------------------------------------------------- *
5  * The software in this package is published under the terms of the LGPL license *
6  * a copy of which has been included with this distribution in the license.txt file. *
7  **************************************************************************************/

8 package org.codehaus.aspectwerkz.util;
9
10 import java.io.Serializable JavaDoc;
11 import java.lang.ref.WeakReference JavaDoc;
12
13 /**
14  * Extends the <code>java.lang.ThreadLocal</code> to be able to add additional functionality. <p/>This classes
15  * enhances the base implementation by: <p/>making it serializable <p/>making it wrap an unwrap the values in a
16  * <code>java.lang.ref.WeakReference</code> to avoid potential memory leaks
17  *
18  * @author <a HREF="mailto:jboner@codehaus.org">Jonas BonŽr </a>
19  */

20 public class SerializableThreadLocal extends java.lang.ThreadLocal JavaDoc implements Serializable JavaDoc {
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 JavaDoc get() {
35         Object JavaDoc ref = super.get();
36         if (ref == null) {
37             return ref;
38         } else {
39             return ((WeakReference JavaDoc) 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 JavaDoc value) {
52         synchronized (this) {
53             super.set(new WeakReference JavaDoc(value));
54         }
55     }
56 }
Popular Tags