This project has retired. For details please refer to its Attic page.
Source code
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,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.reef.util;
020
021import org.apache.reef.io.Tuple;
022
023import java.util.HashSet;
024import java.util.Set;
025
026/**
027 * A helper class that can be used to ensure that objects are only instantiated once.
028 */
029public final class SingletonAsserter {
030
031  private static final Set<Class> ALL_CLASSES = new HashSet<>();
032
033  private static final Set<Class> SINGLETONS_GLOBAL = new HashSet<>();
034
035  private static final Set<Tuple<String, Class>> SINGLETONS_SCOPED = new HashSet<>();
036
037  /**
038   * This class operates purely in static mode.
039   */
040  private SingletonAsserter() {
041  }
042
043  /**
044   * Check if a given class is instantiated only once.
045   * @param clazz Class to check.
046   * @return True if the class was not instantiated before, false otherwise.
047   */
048  public static synchronized boolean assertSingleton(final Class clazz) {
049    return SINGLETONS_GLOBAL.add(clazz) && ALL_CLASSES.add(clazz);
050  }
051
052  /**
053   * Check if given class is singleton within a particular environment or scope.
054   * @param scopeId Environment id, e.g. Driver name or REEF job id.
055   * @param clazz Class that must have no more than 1 instance in that environment.
056   * @return true if the instance is unique within that particular environment, false otherwise.
057   */
058  public static synchronized boolean assertSingleton(final String scopeId, final Class clazz) {
059    ALL_CLASSES.add(clazz);
060    return SINGLETONS_SCOPED.add(new Tuple<>(scopeId, clazz)) && !SINGLETONS_GLOBAL.contains(clazz);
061  }
062}