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 */
018package org.apache.hadoop.hbase.zookeeper;
019
020import java.util.concurrent.CountDownLatch;
021
022/**
023 * Placeholder of an instance which will be accessed by other threads but is not yet created. Thread
024 * safe.
025 */
026class InstancePending<T> {
027  // Based on a subtle part of the Java Language Specification,
028  // in order to avoid a slight overhead of synchronization for each access.
029
030  private final CountDownLatch pendingLatch = new CountDownLatch(1);
031
032  /** Piggybacking on {@code pendingLatch}. */
033  private InstanceHolder<T> instanceHolder;
034
035  private static class InstanceHolder<T> {
036    // The JLS ensures the visibility of a final field and its contents
037    // unless they are exposed to another thread while the construction.
038    final T instance;
039
040    InstanceHolder(T instance) {
041      this.instance = instance;
042    }
043  }
044
045  /**
046   * Returns the instance given by the method {@link #prepare}. This is an uninterruptible blocking
047   * method and the interruption flag will be set just before returning if any.
048   */
049  T get() {
050    InstanceHolder<T> instanceHolder;
051    boolean interrupted = false;
052
053    while ((instanceHolder = this.instanceHolder) == null) {
054      try {
055        pendingLatch.await();
056      } catch (InterruptedException e) {
057        interrupted = true;
058      }
059    }
060
061    if (interrupted) {
062      Thread.currentThread().interrupt();
063    }
064    return instanceHolder.instance;
065  }
066
067  /**
068   * Associates the given instance for the method {@link #get}. This method should be called once,
069   * and {@code instance} should be non-null. This method is expected to call as soon as possible
070   * because the method {@code get} is uninterruptibly blocked until this method is called.
071   */
072  void prepare(T instance) {
073    assert instance != null;
074    instanceHolder = new InstanceHolder<>(instance);
075    pendingLatch.countDown();
076  }
077}