001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018/////////////////////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.utils; 021 022import java.lang.ref.WeakReference; 023 024/** 025 * A wrapper class for {@link WeakReference} that provides a convenient way 026 * to manage weak references to objects. 027 * 028 * <p> 029 * This class encapsulates the creation and retrieval of weak references, 030 * simplifying the common pattern of storing and accessing weakly referenced objects. 031 * </p> 032 * 033 * @param <T> the type of the referenced object 034 */ 035public final class WeakReferenceHolder<T> { 036 037 /** The weak reference to the object. */ 038 private WeakReference<T> reference; 039 040 /** 041 * Constructs a new {@code WeakReferenceHolder} with no initial reference. 042 */ 043 public WeakReferenceHolder() { 044 reference = new WeakReference<>(null); 045 } 046 047 /** 048 * Returns the object held by this weak reference, or {@code null} if 049 * the object has been garbage collected. 050 * 051 * @return the referenced object, or {@code null} if it has been collected 052 */ 053 public T get() { 054 return reference.get(); 055 } 056 057 /** 058 * Updates the referenced object only if the new object is different 059 * from the currently referenced object. After updating, runs the 060 * specified callback if provided. 061 * 062 * @param newObject the new object to reference; 063 * @param afterUpdate a callback to run after updating the reference; 064 */ 065 public void lazyUpdate(T newObject, Runnable afterUpdate) { 066 final T previous = reference.get(); 067 if (previous != newObject) { 068 reference = new WeakReference<>(newObject); 069 afterUpdate.run(); 070 } 071 } 072 073}