1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package org.apache.hadoop.util; 20 21 import org.apache.hadoop.classification.InterfaceAudience; 22 import org.apache.hadoop.classification.InterfaceStability; 23 24 import com.google.common.collect.Interner; 25 import com.google.common.collect.Interners; 26 27 /** 28 * Provides equivalent behavior to String.intern() to optimize performance, 29 * whereby does not consume memory in the permanent generation. 30 */ 31 @InterfaceAudience.Public 32 @InterfaceStability.Stable 33 public class StringInterner { 34 35 /** 36 * Retains a strong reference to each string instance it has interned. 37 */ 38 private final static Interner<String> strongInterner; 39 40 /** 41 * Retains a weak reference to each string instance it has interned. 42 */ 43 private final static Interner<String> weakInterner; 44 45 46 47 static { 48 strongInterner = Interners.newStrongInterner(); 49 weakInterner = Interners.newWeakInterner(); 50 } 51 52 /** 53 * Interns and returns a reference to the representative instance 54 * for any of a collection of string instances that are equal to each other. 55 * Retains strong reference to the instance, 56 * thus preventing it from being garbage-collected. 57 * 58 * @param sample string instance to be interned 59 * @return strong reference to interned string instance 60 */ strongIntern(String sample)61 public static String strongIntern(String sample) { 62 if (sample == null) { 63 return null; 64 } 65 return strongInterner.intern(sample); 66 } 67 68 /** 69 * Interns and returns a reference to the representative instance 70 * for any of a collection of string instances that are equal to each other. 71 * Retains weak reference to the instance, 72 * and so does not prevent it from being garbage-collected. 73 * 74 * @param sample string instance to be interned 75 * @return weak reference to interned string instance 76 */ weakIntern(String sample)77 public static String weakIntern(String sample) { 78 if (sample == null) { 79 return null; 80 } 81 return weakInterner.intern(sample); 82 } 83 84 } 85