001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.base.Equivalence;
022import com.google.common.base.Function;
023import com.google.common.collect.MapMakerInternalMap.InternalEntry;
024import java.util.concurrent.ConcurrentMap;
025
026/**
027 * Contains static methods pertaining to instances of {@link Interner}.
028 *
029 * @author Kevin Bourrillion
030 * @since 3.0
031 */
032@Beta
033@GwtIncompatible
034public final class Interners {
035  private Interners() {}
036
037  /**
038   * Returns a new thread-safe interner which retains a strong reference to each instance it has
039   * interned, thus preventing these instances from being garbage-collected. If this retention is
040   * acceptable, this implementation may perform better than {@link #newWeakInterner}.
041   */
042  public static <E> Interner<E> newStrongInterner() {
043    final ConcurrentMap<E, E> map = new MapMaker().makeMap();
044    return new Interner<E>() {
045      @Override
046      public E intern(E sample) {
047        E canonical = map.putIfAbsent(checkNotNull(sample), sample);
048        return (canonical == null) ? sample : canonical;
049      }
050    };
051  }
052
053  /**
054   * Returns a new thread-safe interner which retains a weak reference to each instance it has
055   * interned, and so does not prevent these instances from being garbage-collected. This most
056   * likely does not perform as well as {@link #newStrongInterner}, but is the best alternative
057   * when the memory usage of that implementation is unacceptable.
058   */
059  @GwtIncompatible("java.lang.ref.WeakReference")
060  public static <E> Interner<E> newWeakInterner() {
061    return new WeakInterner<E>();
062  }
063
064  private static class WeakInterner<E> implements Interner<E> {
065    // MapMaker is our friend, we know about this type
066    private final MapMakerInternalMap<E, Dummy, ?, ?> map =
067        new MapMaker().weakKeys().keyEquivalence(Equivalence.equals()).makeCustomMap();
068
069    @Override
070    public E intern(E sample) {
071      while (true) {
072        // trying to read the canonical...
073        InternalEntry<E, Dummy, ?> entry = map.getEntry(sample);
074        if (entry != null) {
075          E canonical = entry.getKey();
076          if (canonical != null) { // only matters if weak/soft keys are used
077            return canonical;
078          }
079        }
080
081        // didn't see it, trying to put it instead...
082        Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE);
083        if (sneaky == null) {
084          return sample;
085        } else {
086          /* Someone beat us to it! Trying again...
087           *
088           * Technically this loop not guaranteed to terminate, so theoretically (extremely
089           * unlikely) this thread might starve, but even then, there is always going to be another
090           * thread doing progress here.
091           */
092        }
093      }
094    }
095
096    private enum Dummy {
097      VALUE
098    }
099  }
100
101  /**
102   * Returns a function that delegates to the {@link Interner#intern} method of the given interner.
103   *
104   * @since 8.0
105   */
106  public static <E> Function<E, E> asFunction(Interner<E> interner) {
107    return new InternerFunction<E>(checkNotNull(interner));
108  }
109
110  private static class InternerFunction<E> implements Function<E, E> {
111
112    private final Interner<E> interner;
113
114    public InternerFunction(Interner<E> interner) {
115      this.interner = interner;
116    }
117
118    @Override
119    public E apply(E input) {
120      return interner.intern(input);
121    }
122
123    @Override
124    public int hashCode() {
125      return interner.hashCode();
126    }
127
128    @Override
129    public boolean equals(Object other) {
130      if (other instanceof InternerFunction) {
131        InternerFunction<?> that = (InternerFunction<?>) other;
132        return interner.equals(that.interner);
133      }
134
135      return false;
136    }
137  }
138}