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.ReferenceEntry;
024
025import java.util.concurrent.ConcurrentMap;
026
027/**
028 * Contains static methods pertaining to instances of {@link Interner}.
029 *
030 * @author Kevin Bourrillion
031 * @since 3.0
032 */
033@Beta
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}. Note that
041   * unlike {@link String#intern}, using this interner does not consume memory in the permanent
042   * generation.
043   */
044  public static <E> Interner<E> newStrongInterner() {
045    final ConcurrentMap<E, E> map = new MapMaker().makeMap();
046    return new Interner<E>() {
047      @Override
048      public E intern(E sample) {
049        E canonical = map.putIfAbsent(checkNotNull(sample), sample);
050        return (canonical == null) ? sample : canonical;
051      }
052    };
053  }
054
055  /**
056   * Returns a new thread-safe interner which retains a weak reference to each instance it has
057   * interned, and so does not prevent these instances from being garbage-collected. This most
058   * likely does not perform as well as {@link #newStrongInterner}, but is the best alternative
059   * when the memory usage of that implementation is unacceptable. Note that unlike {@link
060   * String#intern}, using this interner does not consume memory in the permanent generation.
061   */
062  @GwtIncompatible("java.lang.ref.WeakReference")
063  public static <E> Interner<E> newWeakInterner() {
064    return new WeakInterner<E>();
065  }
066
067  private static class WeakInterner<E> implements Interner<E> {
068    // MapMaker is our friend, we know about this type
069    private final MapMakerInternalMap<E, Dummy> map =
070        new MapMaker()
071            .weakKeys()
072            .keyEquivalence(Equivalence.equals())
073            .makeCustomMap();
074
075    @Override
076    public E intern(E sample) {
077      while (true) {
078        // trying to read the canonical...
079        ReferenceEntry<E, Dummy> entry = map.getEntry(sample);
080        if (entry != null) {
081          E canonical = entry.getKey();
082          if (canonical != null) { // only matters if weak/soft keys are used
083            return canonical;
084          }
085        }
086
087        // didn't see it, trying to put it instead...
088        Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE);
089        if (sneaky == null) {
090          return sample;
091        } else {
092          /* Someone beat us to it! Trying again...
093           *
094           * Technically this loop not guaranteed to terminate, so theoretically (extremely
095           * unlikely) this thread might starve, but even then, there is always going to be another
096           * thread doing progress here.
097           */
098        }
099      }
100    }
101
102    private enum Dummy {
103      VALUE
104    }
105  }
106
107  /**
108   * Returns a function that delegates to the {@link Interner#intern} method of the given interner.
109   *
110   * @since 8.0
111   */
112  public static <E> Function<E, E> asFunction(Interner<E> interner) {
113    return new InternerFunction<E>(checkNotNull(interner));
114  }
115
116  private static class InternerFunction<E> implements Function<E, E> {
117
118    private final Interner<E> interner;
119
120    public InternerFunction(Interner<E> interner) {
121      this.interner = interner;
122    }
123
124    @Override
125    public E apply(E input) {
126      return interner.intern(input);
127    }
128
129    @Override
130    public int hashCode() {
131      return interner.hashCode();
132    }
133
134    @Override
135    public boolean equals(Object other) {
136      if (other instanceof InternerFunction) {
137        InternerFunction<?> that = (InternerFunction<?>) other;
138        return interner.equals(that.interner);
139      }
140
141      return false;
142    }
143  }
144}