1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.kernel.cache;
16  
17  import com.liferay.portal.kernel.util.StringBundler;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  /**
23   * <a href="ThreadLocalCache.java.html"><b><i>View Source</i></b></a>
24   *
25   * @author Shuyang Zhou
26   */
27  public class ThreadLocalCache<T> {
28  
29      public ThreadLocalCache(String name, Lifecycle lifecycle) {
30          _name = name;
31          _lifecycle = lifecycle;
32      }
33  
34      public T get(String key) {
35          if (_cache == null) {
36              return null;
37          }
38          else {
39              return _cache.get(key);
40          }
41      }
42  
43      public Lifecycle getLifecycle() {
44          return _lifecycle;
45      }
46  
47      public String getName() {
48          return _name;
49      }
50  
51      public void put(String key, T obj) {
52          if (_cache == null) {
53              _cache = new HashMap<String, T>();
54          }
55  
56          _cache.put(key, obj);
57      }
58  
59      public void remove(String key) {
60          if (_cache != null) {
61              _cache.remove(key);
62          }
63      }
64  
65      public void removeAll() {
66          if (_cache != null) {
67              _cache.clear();
68          }
69      }
70  
71      public String toString() {
72          StringBundler sb = new StringBundler(7);
73  
74          sb.append("{cache=");
75          sb.append(_cache.toString());
76          sb.append(", lifecycle=");
77          sb.append(_lifecycle);
78          sb.append(", name=");
79          sb.append(_name);
80          sb.append("}");
81  
82          return sb.toString();
83      }
84  
85      private Map<String, T> _cache;
86      private Lifecycle _lifecycle;
87      private String _name;
88  
89  }