Path: blob/master/debugtools/DDR_VM/src/com/ibm/j9ddr/util/WeakValueMap.java
6005 views
/*******************************************************************************1* Copyright (c) 2009, 2015 IBM Corp. and others2*3* This program and the accompanying materials are made available under4* the terms of the Eclipse Public License 2.0 which accompanies this5* distribution and is available at https://www.eclipse.org/legal/epl-2.0/6* or the Apache License, Version 2.0 which accompanies this distribution and7* is available at https://www.apache.org/licenses/LICENSE-2.0.8*9* This Source Code may also be made available under the following10* Secondary Licenses when the conditions for such availability set11* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU12* General Public License, version 2 with the GNU Classpath13* Exception [1] and GNU General Public License, version 2 with the14* OpenJDK Assembly Exception [2].15*16* [1] https://www.gnu.org/software/classpath/license.html17* [2] http://openjdk.java.net/legal/assembly-exception.html18*19* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception20*******************************************************************************/21package com.ibm.j9ddr.util;2223import java.lang.ref.ReferenceQueue;24import java.lang.ref.SoftReference;25import java.util.HashMap;26import java.util.Map;2728/**29* Map that weakly references values.30*31* @author andhall32*33*/34public class WeakValueMap<K,V>35{36private final Map<K,ReferenceType<K,V>> map = new HashMap<K,ReferenceType<K,V>>();3738private final ReferenceQueue<V> refQueue = new ReferenceQueue<V>();3940public void put(K key,V value)41{42cleanupTax();4344map.put(key, new ReferenceType<K,V>(key,value,refQueue));45}4647public V get(K key)48{49cleanupTax();5051ReferenceType<K,V> entry = map.get(key);5253if (entry != null) {54return entry.get();55} else {56return null;57}58}5960public void clear()61{62map.clear();63}6465/* Every operation is taxed to clean-up the refQueue. Otherwise we'll leak reference objects */66@SuppressWarnings("unchecked")67private void cleanupTax()68{69ReferenceType<K,V> queued = null;7071while ( (queued = (ReferenceType<K, V>) refQueue.poll()) != null) {72map.remove(queued.key);73}74}7576private static class ReferenceType<K,V> extends SoftReference<V>77{78public final K key;7980public ReferenceType(K key, V value, ReferenceQueue<V> refQueue)81{82super(value,refQueue);83this.key = key;84}85}86}878889