KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > picocontainer > defaults > ThreadLocalCyclicDependencyGuard


1 /*****************************************************************************
2  * Copyright (c) PicoContainer Organization. All rights reserved. *
3  * ------------------------------------------------------------------------- *
4  * The software in this package is published under the terms of the BSD *
5  * style license a copy of which has been included with this distribution in *
6  * the LICENSE.txt file. *
7  * *
8  * Original code by Joerg Schaible *
9  *****************************************************************************/

10
11 package org.picocontainer.defaults;
12
13 /**
14  * Abstract utility class to detect recursion cycles.
15  * Derive from this class and implement {@link ThreadLocalCyclicDependencyGuard#run}.
16  * The method will be called by {@link ThreadLocalCyclicDependencyGuard#observe}. Select
17  * an appropriate guard for your scope. Any {@link ObjectReference} can be
18  * used as long as it is initialized with <code>Boolean.FALSE</code>.
19  *
20  * @author J&ouml;rg Schaible
21  * @since 1.1
22  */

23 public abstract class ThreadLocalCyclicDependencyGuard extends ThreadLocal JavaDoc implements CyclicDependencyGuard {
24
25     /**
26      * {@inheritDoc}
27      * @see java.lang.ThreadLocal#initialValue()
28      */

29     protected Object JavaDoc initialValue() {
30         return Boolean.FALSE;
31     }
32     /**
33      * Derive from this class and implement this function with the functionality
34      * to observe for a dependency cycle.
35      *
36      * @return a value, if the functionality result in an expression,
37      * otherwise just return <code>null</code>
38      */

39     public abstract Object JavaDoc run();
40     
41     /**
42      * Call the observing function. The provided guard will hold the {@link Boolean} value.
43      * If the guard is already <code>Boolean.TRUE</code> a {@link CyclicDependencyException}
44      * will be thrown.
45      *
46      * @param stackFrame the current stack frame
47      * @return the result of the <code>run</code> method
48      */

49     public final Object JavaDoc observe(Class JavaDoc stackFrame) {
50         if (Boolean.TRUE.equals(get())) {
51             throw new CyclicDependencyException(stackFrame);
52         }
53         Object JavaDoc result = null;
54         try {
55             set(Boolean.TRUE);
56             result = run();
57         } catch (final CyclicDependencyException e) {
58             e.push(stackFrame);
59             throw e;
60         } finally {
61             set(Boolean.FALSE);
62         }
63         return result;
64     }
65 }
66
Popular Tags