Interner.java revision 1019
306N/A/*
306N/A * CDDL HEADER START
306N/A *
306N/A * The contents of this file are subject to the terms of the
306N/A * Common Development and Distribution License (the "License").
306N/A * You may not use this file except in compliance with the License.
306N/A *
306N/A * See LICENSE.txt included in this distribution for the specific
306N/A * language governing permissions and limitations under the License.
306N/A *
306N/A * When distributing Covered Code, include this CDDL HEADER in each
306N/A * file and include the License file at LICENSE.txt.
306N/A * If applicable, add the following below this CDDL HEADER, with the
306N/A * fields enclosed by brackets "[]" replaced with your own identifying
306N/A * information: Portions Copyright [yyyy] [name of copyright owner]
306N/A *
306N/A * CDDL HEADER END
306N/A */
306N/A
306N/A/*
306N/A * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
306N/A * Use is subject to license terms.
306N/A */
306N/A
306N/Apackage org.opensolaris.opengrok.util;
306N/A
306N/Aimport java.util.HashMap;
306N/Aimport java.util.Map;
306N/A
306N/A/**
306N/A * <p>
306N/A * Helper class that interns objects, that is, returns a canonical
306N/A * representation of the objects. This works similar to
306N/A * {@link java.lang.String#intern}, but it stores the canonical objects on
306N/A * the heap instead of in the permgen space to address bug #15956.
306N/A * </p>
306N/A *
306N/A * <p>
306N/A * Instances of this class are not thread safe.
306N/A * </p>
306N/A *
306N/A * <p>
306N/A * In contrast to {@link java.lang.String#intern}, this class does not attempt
306N/A * to make objects that are not referenced anymore eligible for garbage
306N/A * collection. Hence, references to instances of this class should not be
306N/A * held longer than necessary.
306N/A * </p>
*
* @param <T> the type of the objects being interned by the instance
*/
public class Interner<T> {
/** Map of interned objects. Key and value contain the same object. */
private final Map<T, T> map = new HashMap<T, T>();
/**
* <p>
* Intern an object and return a canonical instance of it. For two objects
* {@code o1} and {@code o2}, the following always evaluates to
* {@code true}:
* </p>
*
* <pre>
* ( o1 == null ) ?
* ( intern(o1) == null ) :
* o1.equals(o2) == ( intern(o1) == intern(o2) )
* </pre>
*
* @param instance the object to intern
* @return a canonical representation of {@code instance}
*/
public T intern(T instance) {
if (instance == null) {
return null;
}
T interned = map.get(instance);
if (interned == null) {
interned = instance;
map.put(interned, interned);
}
return interned;
}
}