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