2121import java .io .IOException ;
2222import java .io .Serializable ;
2323import java .util .List ;
24+ import java .util .concurrent .atomic .AtomicBoolean ;
2425
2526/**
2627 * @author Robert HG (254963746@qq.com) on 5/16/15.
@@ -234,6 +235,7 @@ protected void doClose() {
234235 public class PathChildrenListener {
235236 private PathChildrenCache childrenCache ;
236237 private PathChildrenCacheListener childrenCacheListener ;
238+ private AtomicBoolean start = new AtomicBoolean (false );
237239
238240 public PathChildrenListener (String path , final ChildListener listener ) {
239241 childrenCache = new PathChildrenCache (client , path , true );
@@ -259,18 +261,22 @@ public void childEvent(CuratorFramework c, PathChildrenCacheEvent event)
259261
260262 public void startListener () {
261263 try {
262- childrenCache .start (PathChildrenCache .StartMode .POST_INITIALIZED_EVENT );
263- childrenCache .getListenable ().addListener (childrenCacheListener );
264+ if (start .compareAndSet (false , true )) {
265+ childrenCache .start (PathChildrenCache .StartMode .POST_INITIALIZED_EVENT );
266+ childrenCache .getListenable ().addListener (childrenCacheListener );
267+ }
264268 } catch (Exception e ) {
265269 throw new ZkException (e );
266270 }
267271 }
268272
269273 public void stopListener () {
270274 try {
271- childrenCache .getListenable ().removeListener (childrenCacheListener );
272- childrenCache .clear ();
273- childrenCache .close ();
275+ if (start .compareAndSet (true , false )) {
276+ childrenCache .getListenable ().removeListener (childrenCacheListener );
277+ childrenCache .clear ();
278+ childrenCache .close ();
279+ }
274280 } catch (IOException e ) {
275281 throw new ZkException (e );
276282 }
@@ -290,9 +296,9 @@ public void nodeChanged() throws Exception {
290296
291297 Object data = nodeCache .getCurrentData ().getData ();
292298
293- if (data == null ){
299+ if (data == null ) {
294300 listener .dataDeleted (path );
295- }else {
301+ } else {
296302 listener .dataChange (path , data );
297303 }
298304 }
0 commit comments