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
019 package org.apache.hadoop.util;
020
021 import org.apache.hadoop.classification.InterfaceAudience;
022 import org.apache.hadoop.classification.InterfaceStability;
023
024 import com.google.common.collect.Interner;
025 import com.google.common.collect.Interners;
026
027 /**
028 * Provides equivalent behavior to String.intern() to optimize performance,
029 * whereby does not consume memory in the permanent generation.
030 */
031 @InterfaceAudience.Public
032 @InterfaceStability.Stable
033 public class StringInterner {
034
035 /**
036 * Retains a strong reference to each string instance it has interned.
037 */
038 private final static Interner<String> strongInterner;
039
040 /**
041 * Retains a weak reference to each string instance it has interned.
042 */
043 private final static Interner<String> weakInterner;
044
045
046
047 static {
048 strongInterner = Interners.newStrongInterner();
049 weakInterner = Interners.newWeakInterner();
050 }
051
052 /**
053 * Interns and returns a reference to the representative instance
054 * for any of a collection of string instances that are equal to each other.
055 * Retains strong reference to the instance,
056 * thus preventing it from being garbage-collected.
057 *
058 * @param sample string instance to be interned
059 * @return strong reference to interned string instance
060 */
061 public static String strongIntern(String sample) {
062 if (sample == null) {
063 return null;
064 }
065 return strongInterner.intern(sample);
066 }
067
068 /**
069 * Interns and returns a reference to the representative instance
070 * for any of a collection of string instances that are equal to each other.
071 * Retains weak reference to the instance,
072 * and so does not prevent it from being garbage-collected.
073 *
074 * @param sample string instance to be interned
075 * @return weak reference to interned string instance
076 */
077 public static String weakIntern(String sample) {
078 if (sample == null) {
079 return null;
080 }
081 return weakInterner.intern(sample);
082 }
083
084 }