View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.zookeeper;
20  
21  import org.apache.zookeeper.WatchedEvent;
22  import org.apache.zookeeper.Watcher;
23  
24  /**
25   * Placeholder of a watcher which might be triggered before the instance is not yet created.
26   * <p>
27   * {@code ZooKeeper} starts its event thread within its constructor (and that is an anti-pattern),
28   * and the watcher passed to the constructor might be called back by the event thread
29   * before you get the instance of {@code ZooKeeper} from the constructor.
30   * If your watcher calls methods of {@code ZooKeeper},
31   * pass this placeholder to the constructor of the {@code ZooKeeper},
32   * create your watcher using the instance of {@code ZooKeeper},
33   * and then call the method {@code PendingWatcher.prepare}.
34   */
35  class PendingWatcher implements Watcher {
36    private final InstancePending<Watcher> pending = new InstancePending<Watcher>();
37  
38    @Override
39    public void process(WatchedEvent event) {
40      pending.get().process(event);
41    }
42  
43    /**
44     * Associates the substantial watcher of processing events.
45     * This method should be called once, and {@code watcher} should be non-null.
46     * This method is expected to call as soon as possible
47     * because the event processing, being invoked by the ZooKeeper event thread,
48     * is uninterruptibly blocked until this method is called.
49     */
50    void prepare(Watcher watcher) {
51      pending.prepare(watcher);
52    }
53  }