View Javadoc

1   /*
2    * Copyright 2007-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springbyexample.bean.scope.thread;
18  
19  import java.util.HashMap;
20  import java.util.LinkedHashMap;
21  import java.util.Map;
22  
23  import org.slf4j.Logger;
24  import org.slf4j.LoggerFactory;
25  import org.springframework.util.Assert;
26  
27  /**
28   * Thread scope attributes.
29   * 
30   * @author David Winterfeldt
31   */
32  public class ThreadScopeAttributes {
33      
34      final Logger logger = LoggerFactory.getLogger(ThreadScopeAttributes.class);
35      
36      protected final Map<String, Object> hBeans = new HashMap<String, Object>();
37      protected final Map<String, Runnable> hRequestDestructionCallbacks = new LinkedHashMap<String, Runnable>();
38  
39      /**
40       * Gets bean <code>Map</code>.
41       */
42      protected final Map<String, Object> getBeanMap() {
43          return hBeans;
44      }
45  
46      /**
47       * Register the given callback as to be executed after request completion.
48       * 
49       * @param   name        The name of the bean.
50       * @param   callback    The callback of the bean to be executed for destruction.
51       */
52      protected final void registerRequestDestructionCallback(String name, Runnable callback) {
53          Assert.notNull(name, "Name must not be null");
54          Assert.notNull(callback, "Callback must not be null");
55          
56          hRequestDestructionCallbacks.put(name, callback);
57      }
58  
59      /**
60       * Clears beans and processes all bean destruction callbacks.
61       */
62      protected final void clear() {
63          processDestructionCallbacks();
64          
65          hBeans.clear();   
66      }
67  
68      /**
69       * Processes all bean destruction callbacks.
70       */
71      private final void processDestructionCallbacks() {
72          for (String name: hRequestDestructionCallbacks.keySet()) {
73              Runnable callback = hRequestDestructionCallbacks.get(name);
74              
75              logger.debug("Performing destruction callback for '" + name + "' bean" + 
76                       " on thread '" + Thread.currentThread().getName() + "'.");
77              
78              callback.run();
79          }
80          
81          hRequestDestructionCallbacks.clear();
82      }
83  
84  }