1 package org.apache.helix.manager.zk;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.locks.ReadWriteLock;
28 import java.util.concurrent.locks.ReentrantReadWriteLock;
29
30 import org.apache.helix.store.zk.ZNode;
31 import org.apache.helix.util.HelixUtil;
32 import org.apache.zookeeper.data.Stat;
33
34
35 public abstract class Cache<T>
36 {
37 final ReadWriteLock _lock;
38 final ConcurrentHashMap<String, ZNode> _cache;
39
40 public Cache()
41 {
42 _lock = new ReentrantReadWriteLock();
43 _cache = new ConcurrentHashMap<String, ZNode>();
44 }
45
46 public void addToParentChildSet(String parentPath, String childName)
47 {
48 ZNode znode = _cache.get(parentPath);
49 if (znode != null)
50 {
51 znode.addChild(childName);
52 }
53 }
54
55 public void addToParentChildSet(String parentPath, List<String> childNames)
56 {
57 if (childNames != null && !childNames.isEmpty())
58 {
59 ZNode znode = _cache.get(parentPath);
60 if (znode != null)
61 {
62 znode.addChildren(childNames);
63 }
64 }
65 }
66
67 public void removeFromParentChildSet(String parentPath, String name)
68 {
69 ZNode zNode = _cache.get(parentPath);
70 if (zNode != null)
71 {
72 zNode.removeChild(name);
73 }
74 }
75
76 public boolean exists(String path)
77 {
78 return _cache.containsKey(path);
79 }
80
81 public ZNode get(String path)
82 {
83 try
84 {
85 _lock.readLock().lock();
86 return _cache.get(path);
87 }
88 finally
89 {
90 _lock.readLock().unlock();
91 }
92 }
93
94 public void lockWrite()
95 {
96 _lock.writeLock().lock();
97 }
98
99 public void unlockWrite()
100 {
101 _lock.writeLock().unlock();
102 }
103
104 public void lockRead()
105 {
106 _lock.readLock().lock();
107 }
108
109 public void unlockRead()
110 {
111 _lock.readLock().unlock();
112 }
113
114 public void purgeRecursive(String path)
115 {
116 try
117 {
118 _lock.writeLock().lock();
119
120 String parentPath = HelixUtil.getZkParentPath(path);
121 String name = HelixUtil.getZkName(path);
122 removeFromParentChildSet(parentPath, name);
123
124 ZNode znode = _cache.remove(path);
125 if (znode != null)
126 {
127
128 Set<String> childNames = znode.getChildSet();
129 for (String childName : childNames)
130 {
131 String childPath = path + "/" + childName;
132 purgeRecursive(childPath);
133 }
134 }
135 }
136 finally
137 {
138 _lock.writeLock().unlock();
139 }
140 }
141
142 public void reset()
143 {
144 try
145 {
146 _lock.writeLock().lock();
147 _cache.clear();
148 }
149 finally
150 {
151 _lock.writeLock().unlock();
152 }
153 }
154
155 public abstract void update(String path, T data, Stat stat);
156
157 public abstract void updateRecursive(String path);
158
159
160
161 public Map<String, ZNode> getCache()
162 {
163 return _cache;
164 }
165
166 }