
com.cedarsoftware.util.TrackingMap Maven / Gradle / Ivy
The newest version!
package com.cedarsoftware.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A wrapper around a {@link Map} that tracks which keys have been accessed via {@code get} or {@code containsKey} methods.
* This is useful for scenarios where it's necessary to monitor usage patterns of keys in a map,
* such as identifying unused entries or optimizing memory usage by expunging rarely accessed keys.
*
*
* Usage Example:
*
* {@code
* Map originalMap = new HashMap<>();
* originalMap.put("apple", 1);
* originalMap.put("banana", 2);
* originalMap.put("cherry", 3);
*
* TrackingMap trackingMap = new TrackingMap<>(originalMap);
*
* // Access some keys
* trackingMap.get("apple");
* trackingMap.containsKey("banana");
*
* // Expunge unused keys
* trackingMap.expungeUnused();
*
* // Now, "cherry" has been removed as it was not accessed
* System.out.println(trackingMap.keySet()); // Outputs: [apple, banana]
* }
*
*
* Thread Safety: This class is not thread-safe. If multiple threads access a {@code TrackingMap}
* concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally.
*
*
*
* Note: The {@link #expungeUnused()} method removes all entries that have not been accessed via
* {@link #get(Object)} or {@link #containsKey(Object)} since the map was created or since the last call to
* {@code expungeUnused()}.
*
*
* @param the type of keys maintained by this map
* @param the type of mapped values
*
* @author
* Sean Kellner
*
* Copyright (c) Cedar Software LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* License
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class TrackingMap implements Map {
private final Map internalMap;
/**
* Tracks all keys that were read via {@link #get(Object)} or
* {@link #containsKey(Object)}. Stored as {@code Object} to avoid
* {@link ClassCastException} if callers supply a key of a different type.
*/
private final Set
© 2015 - 2025 Weber Informatics LLC | Privacy Policy