All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.helger.commons.lang.ClassHierarchyCache Maven / Gradle / Ivy

There is a newer version: 9.5.5
Show newest version
/**
 * Copyright (C) 2014-2016 Philip Helger (www.helger.com)
 * philip[at]helger[dot]com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.helger.commons.lang;

import java.lang.ref.WeakReference;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.ThreadSafe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.PresentForCodeCoverage;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.ext.CommonsArrayList;
import com.helger.commons.collection.ext.CommonsLinkedHashSet;
import com.helger.commons.collection.ext.ICommonsList;
import com.helger.commons.collection.ext.ICommonsMap;
import com.helger.commons.collection.ext.ICommonsOrderedSet;
import com.helger.commons.collection.ext.ICommonsSet;
import com.helger.commons.collection.impl.LRUMap;
import com.helger.commons.collection.iterate.IIterableIterator;
import com.helger.commons.concurrent.SimpleReadWriteLock;
import com.helger.commons.state.EChange;
import com.helger.commons.string.ToStringGenerator;

/**
 * A small class hierarchy cache
 *
 * @author Philip Helger
 */
@ThreadSafe
public final class ClassHierarchyCache
{
  @Immutable
  private static final class ClassList implements Iterable >>
  {
    // Store it in the correct order, but without duplicates
    private final ICommonsList >> m_aList = new CommonsArrayList<> ();

    public ClassList (@Nonnull final Class  aClass)
    {
      ValueEnforcer.notNull (aClass, "Class");

      // Check the whole class hierarchy of the source class
      final ICommonsOrderedSet > aUniqueOrderedClasses = new CommonsLinkedHashSet<> ();
      final ICommonsList > aOpenSrc = new CommonsArrayList<> ();
      aOpenSrc.add (aClass);
      while (!aOpenSrc.isEmpty ())
      {
        final Class  aCurClass = aOpenSrc.removeFirst ();
        aUniqueOrderedClasses.add (aCurClass);

        // Add super-classes and interfaces
        // Super-classes have precedence over interfaces!
        for (final Class  aInterface : aCurClass.getInterfaces ())
          aOpenSrc.add (0, aInterface);
        if (aCurClass.getSuperclass () != null)
          aOpenSrc.add (0, aCurClass.getSuperclass ());
      }

      // Now convert to list of WeakReference
      for (final Class  aCurClass : aUniqueOrderedClasses)
        m_aList.add (new WeakReference<> (aCurClass));
    }

    @Nonnull
    @ReturnsMutableCopy
    public ICommonsOrderedSet > getAsSet ()
    {
      // Use a linked hash set, to maintain the order
      final ICommonsOrderedSet > ret = new CommonsLinkedHashSet<> (m_aList.size ());
      for (final WeakReference > aRef : m_aList)
      {
        final Class  aClass = aRef.get ();
        if (aClass != null)
          ret.add (aClass);
      }
      return ret;
    }

    @Nonnull
    @ReturnsMutableCopy
    public ICommonsList > getAsList ()
    {
      // Use a list that may contain duplicates
      final ICommonsList > ret = new CommonsArrayList<> (m_aList.size ());
      for (final WeakReference > aRef : m_aList)
      {
        final Class  aClass = aRef.get ();
        if (aClass != null)
          ret.add (aClass);
      }
      return ret;
    }

    @Nonnull
    public IIterableIterator >> iterator ()
    {
      return m_aList.iterator2 ();
    }

    @Override
    public String toString ()
    {
      return new ToStringGenerator (this).append ("list", m_aList).toString ();
    }
  }

  private static final Logger s_aLogger = LoggerFactory.getLogger (ClassHierarchyCache.class);

  private static final SimpleReadWriteLock s_aRWLock = new SimpleReadWriteLock ();
  @GuardedBy ("s_aRWLock")
  private static final ICommonsMap  s_aClassHierarchy = new LRUMap<> (1000);

  @PresentForCodeCoverage
  private static final ClassHierarchyCache s_aInstance = new ClassHierarchyCache ();

  private ClassHierarchyCache ()
  {}

  /**
   * It's important to clear the cache upon application shutdown, because for
   * web applications, keeping a cache of classes may prevent the web
   * application from unloading
   *
   * @return {@link EChange}
   */
  @Nonnull
  public static EChange clearCache ()
  {
    return s_aRWLock.writeLocked ( () -> {
      if (s_aClassHierarchy.isEmpty ())
        return EChange.UNCHANGED;
      s_aClassHierarchy.clear ();

      if (s_aLogger.isDebugEnabled ())
        s_aLogger.debug ("Cache was cleared: " + ClassHierarchyCache.class.getName ());
      return EChange.CHANGED;
    });
  }

  @Nonnull
  private static ClassList _getClassList (@Nonnull final Class  aClass)
  {
    ValueEnforcer.notNull (aClass, "Class");
    final String sKey = aClass.getName ();

    // Get or update from cache
    ClassList aClassList = s_aRWLock.readLocked ( () -> s_aClassHierarchy.get (sKey));

    if (aClassList == null)
    {
      aClassList = s_aRWLock.writeLocked ( () -> {
        // try again in write lock
        return s_aClassHierarchy.computeIfAbsent (sKey, x -> new ClassList (aClass));
      });
    }
    return aClassList;
  }

  /**
   * Get the complete super class hierarchy of the passed class including all
   * super classes and all interfaces of the passed class and of all parent
   * classes.
   *
   * @param aClass
   *        The source class to get the hierarchy from.
   * @return A non-null and non-empty Set containing the passed
   *         class and all super classes, and all super-interfaces.
   */
  @Nonnull
  @ReturnsMutableCopy
  public static ICommonsSet > getClassHierarchy (@Nonnull final Class  aClass)
  {
    return _getClassList (aClass).getAsSet ();
  }

  /**
   * Get the complete super class hierarchy of the passed class including all
   * super classes and all interfaces of the passed class and of all parent
   * classes.
   *
   * @param aClass
   *        The source class to get the hierarchy from.
   * @return A non-null and non-empty list containing the passed
   *         class and all super classes, and all super-interfaces. Duplicates
   *         were already removed.
   */
  @Nonnull
  @ReturnsMutableCopy
  public static ICommonsList > getClassHierarchyList (@Nonnull final Class  aClass)
  {
    return _getClassList (aClass).getAsList ();
  }

  /**
   * Iterate the complete super class hierarchy of the passed class including
   * all super classes and all interfaces of the passed class and of all parent
   * classes.
   *
   * @param aClass
   *        The source class to get the hierarchy from.
   * @return A non-null and non-empty list containing the passed
   *         class and all super classes, and all super-interfaces. Duplicates
   *         were already removed.
   */
  @Nonnull
  public static Iterable >> getClassHierarchyIterator (@Nonnull final Class  aClass)
  {
    return _getClassList (aClass);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy