001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.zookeeper;
020
021import org.apache.zookeeper.WatchedEvent;
022import org.apache.zookeeper.Watcher;
023
024/**
025 * Placeholder of a watcher which might be triggered before the instance is not yet created.
026 * <p>
027 * {@code ZooKeeper} starts its event thread within its constructor (and that is an anti-pattern),
028 * and the watcher passed to the constructor might be called back by the event thread
029 * before you get the instance of {@code ZooKeeper} from the constructor.
030 * If your watcher calls methods of {@code ZooKeeper},
031 * pass this placeholder to the constructor of the {@code ZooKeeper},
032 * create your watcher using the instance of {@code ZooKeeper},
033 * and then call the method {@code PendingWatcher.prepare}.
034 */
035class PendingWatcher implements Watcher {
036  private final InstancePending<Watcher> pending = new InstancePending<>();
037
038  @Override
039  public void process(WatchedEvent event) {
040    pending.get().process(event);
041  }
042
043  /**
044   * Associates the substantial watcher of processing events.
045   * This method should be called once, and {@code watcher} should be non-null.
046   * This method is expected to call as soon as possible
047   * because the event processing, being invoked by the ZooKeeper event thread,
048   * is uninterruptibly blocked until this method is called.
049   */
050  void prepare(Watcher watcher) {
051    pending.prepare(watcher);
052  }
053}