
org.apache.commons.collections4.map.AbstractReferenceMap Maven / Gradle / Ivy
Show all versions of commons-collections4 Show documentation
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
package org.apache.commons.collections4.map;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.keyvalue.DefaultMapEntry;
/**
* An abstract implementation of a hash-based map that allows the entries to
* be removed by the garbage collector.
*
* This class implements all the features necessary for a subclass reference
* hash-based map. Key-value entries are stored in instances of the
* {@code ReferenceEntry} class which can be overridden and replaced.
* The iterators can similarly be replaced, without the need to replace the KeySet,
* EntrySet and Values view classes.
*
*
* Overridable methods are provided to change the default hashing behavior, and
* to change how entries are added to and removed from the map. Hopefully, all you
* need for unusual subclasses is here.
*
*
* When you construct an {@code AbstractReferenceMap}, you can specify what
* kind of references are used to store the map's keys and values.
* If non-hard references are used, then the garbage collector can remove
* mappings if a key or value becomes unreachable, or if the JVM's memory is
* running low. For information on how the different reference types behave,
* see {@link Reference}.
*
*
* Different types of references can be specified for keys and values.
* The keys can be configured to be weak but the values hard,
* in which case this class will behave like a
*
* {@code WeakHashMap}. However, you can also specify hard keys and
* weak values, or any other combination. The default constructor uses
* hard keys and soft values, providing a memory-sensitive cache.
*
*
* This {@link Map} implementation does not allow null elements.
* Attempting to add a null key or value to the map will raise a
* {@code NullPointerException}.
*
*
* All the available iterators can be reset back to the start by casting to
* {@code ResettableIterator} and calling {@code reset()}.
*
*
* This implementation is not synchronized.
* You can use {@link java.util.Collections#synchronizedMap} to
* provide synchronized access to a {@code ReferenceMap}.
*
*
* @param the type of the keys in this map
* @param the type of the values in this map
* @see java.lang.ref.Reference
* @since 3.1 (extracted from ReferenceMap in 3.0)
*/
public abstract class AbstractReferenceMap extends AbstractHashedMap {
/**
* Base iterator class.
*/
static class ReferenceBaseIterator {
/** The parent map */
final AbstractReferenceMap parent;
// These fields keep track of where we are in the table.
int index;
ReferenceEntry next;
ReferenceEntry current;
// These Object fields provide hard references to the
// current and next entry; this assures that if hasNext()
// returns true, next() will actually return a valid element.
K currentKey;
K nextKey;
V currentValue;
V nextValue;
int expectedModCount;
ReferenceBaseIterator(final AbstractReferenceMap parent) {
this.parent = parent;
index = !parent.isEmpty() ? parent.data.length : 0;
// have to do this here! size() invocation above
// may have altered the modCount.
expectedModCount = parent.modCount;
}
private void checkMod() {
if (parent.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
protected ReferenceEntry currentEntry() {
checkMod();
return current;
}
public boolean hasNext() {
checkMod();
while (nextNull()) {
ReferenceEntry e = next;
int i = index;
while (e == null && i > 0) {
i--;
e = (ReferenceEntry) parent.data[i];
}
next = e;
index = i;
if (e == null) {
return false;
}
nextKey = e.getKey();
nextValue = e.getValue();
if (nextNull()) {
next = next.next();
}
}
return true;
}
protected ReferenceEntry nextEntry() {
checkMod();
if (nextNull() && !hasNext()) {
throw new NoSuchElementException();
}
current = next;
next = next.next();
currentKey = nextKey;
currentValue = nextValue;
nextKey = null;
nextValue = null;
return current;
}
private boolean nextNull() {
return nextKey == null || nextValue == null;
}
public void remove() {
checkMod();
if (current == null) {
throw new IllegalStateException();
}
parent.remove(currentKey);
current = null;
currentKey = null;
currentValue = null;
expectedModCount = parent.modCount;
}
}
/**
* A MapEntry implementation for the map.
*
* If getKey() or getValue() returns null, it means
* the mapping is stale and should be removed.
*
*
* @param the type of the keys
* @param the type of the values
* @since 3.1
*/
protected static class ReferenceEntry extends HashEntry {
/** The parent map */
private final AbstractReferenceMap parent;
/**
* Creates a new entry object for the ReferenceMap.
*
* @param parent the parent map
* @param next the next entry in the hash bucket
* @param hashCode the hash code of the key
* @param key the key
* @param value the value
*/
public ReferenceEntry(final AbstractReferenceMap parent, final HashEntry next,
final int hashCode, final K key, final V value) {
super(next, hashCode, null, null);
this.parent = parent;
this.key = toReference(parent.keyType, key, hashCode);
this.value = toReference(parent.valueType, value, hashCode); // the key hashCode is passed in deliberately
}
/**
* Compares this map entry to another.
*
* This implementation uses {@code isEqualKey} and
* {@code isEqualValue} on the main map for comparison.
*
*
* @param obj the other map entry to compare to
* @return true if equal, false if not
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Map.Entry)) {
return false;
}
final Map.Entry, ?> entry = (Map.Entry, ?>) obj;
final Object entryKey = entry.getKey(); // convert to hard reference
final Object entryValue = entry.getValue(); // convert to hard reference
if (entryKey == null || entryValue == null) {
return false;
}
// compare using map methods, aiding identity subclass
// note that key is direct access and value is via method
return parent.isEqualKey(entryKey, key) &&
parent.isEqualValue(entryValue, getValue());
}
/**
* Gets the key from the entry.
* This method dereferences weak and soft keys and thus may return null.
*
* @return the key, which may be null if it was garbage collected
*/
@Override
@SuppressWarnings("unchecked")
public K getKey() {
return (K) (parent.keyType == ReferenceStrength.HARD ? key : ((Reference) key).get());
}
/**
* Gets the value from the entry.
* This method dereferences weak and soft value and thus may return null.
*
* @return the value, which may be null if it was garbage collected
*/
@Override
@SuppressWarnings("unchecked")
public V getValue() {
return (V) (parent.valueType == ReferenceStrength.HARD ? value : ((Reference) value).get());
}
/**
* Gets the hash code of the entry using temporary hard references.
*
* This implementation uses {@code hashEntry} on the main map.
*
* @return the hash code of the entry
*/
@Override
public int hashCode() {
return parent.hashEntry(getKey(), getValue());
}
/**
* Gets the next entry in the bucket.
*
* @return the next entry in the bucket
*/
protected ReferenceEntry next() {
return (ReferenceEntry) next;
}
/**
* This method can be overridden to provide custom logic to purge value
*/
protected void nullValue() {
value = null;
}
/**
* This is the callback for custom "after purge" logic
*/
protected void onPurge() {
// empty
}
/**
* Purges the specified reference
* @param ref the reference to purge
* @return true or false
*/
protected boolean purge(final Reference> ref) {
boolean r = parent.keyType != ReferenceStrength.HARD && key == ref;
r = r || parent.valueType != ReferenceStrength.HARD && value == ref;
if (r) {
if (parent.keyType != ReferenceStrength.HARD) {
((Reference>) key).clear();
}
if (parent.valueType != ReferenceStrength.HARD) {
((Reference>) value).clear();
} else if (parent.purgeValues) {
nullValue();
}
}
return r;
}
/**
* Sets the value of the entry.
*
* @param value the object to store
* @return the previous value
*/
@Override
@SuppressWarnings("unchecked")
public V setValue(final V value) {
final V old = getValue();
if (parent.valueType != ReferenceStrength.HARD) {
((Reference) this.value).clear();
}
this.value = toReference(parent.valueType, value, hashCode);
return old;
}
/**
* Constructs a reference of the given type to the given referent.
* The reference is registered with the queue for later purging.
*
* @param the type of the referenced object
* @param type HARD, SOFT or WEAK
* @param referent the object to refer to
* @param hash the hash code of the key of the mapping;
* this number might be different from referent.hashCode() if
* the referent represents a value and not a key
* @return the reference to the object
*/
protected Object toReference(final ReferenceStrength type, final T referent, final int hash) {
switch (type) {
case HARD:
return referent;
case SOFT:
return new SoftRef<>(hash, referent, parent.queue);
case WEAK:
return new WeakRef<>(hash, referent, parent.queue);
default:
break;
}
throw new Error();
}
}
/**
* EntrySet implementation.
*/
static class ReferenceEntrySet extends EntrySet {
protected ReferenceEntrySet(final AbstractHashedMap parent) {
super(parent);
}
@Override
public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override
public T[] toArray(final T[] arr) {
// special implementation to handle disappearing entries
final ArrayList> list = new ArrayList<>(size());
for (final Map.Entry entry : this) {
list.add(new DefaultMapEntry<>(entry));
}
return list.toArray(arr);
}
}
/**
* The EntrySet iterator.
*/
static class ReferenceEntrySetIterator
extends ReferenceBaseIterator implements Iterator> {
ReferenceEntrySetIterator(final AbstractReferenceMap parent) {
super(parent);
}
@Override
public Map.Entry next() {
return nextEntry();
}
}
/**
* KeySet implementation.
*/
static class ReferenceKeySet extends KeySet {
protected ReferenceKeySet(final AbstractHashedMap parent) {
super(parent);
}
@Override
public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override
public T[] toArray(final T[] arr) {
// special implementation to handle disappearing keys
final List list = new ArrayList<>(size());
forEach(list::add);
return list.toArray(arr);
}
}
/**
* The keySet iterator.
*/
static class ReferenceKeySetIterator extends ReferenceBaseIterator implements Iterator {
@SuppressWarnings("unchecked")
ReferenceKeySetIterator(final AbstractReferenceMap parent) {
super((AbstractReferenceMap) parent);
}
@Override
public K next() {
return nextEntry().getKey();
}
}
/**
* The MapIterator implementation.
*/
static class ReferenceMapIterator extends ReferenceBaseIterator implements MapIterator {
protected ReferenceMapIterator(final AbstractReferenceMap parent) {
super(parent);
}
@Override
public K getKey() {
final HashEntry current = currentEntry();
if (current == null) {
throw new IllegalStateException(GETKEY_INVALID);
}
return current.getKey();
}
@Override
public V getValue() {
final HashEntry current = currentEntry();
if (current == null) {
throw new IllegalStateException(GETVALUE_INVALID);
}
return current.getValue();
}
@Override
public K next() {
return nextEntry().getKey();
}
@Override
public V setValue(final V value) {
final HashEntry current = currentEntry();
if (current == null) {
throw new IllegalStateException(SETVALUE_INVALID);
}
return current.setValue(value);
}
}
/**
* Enumerates reference types.
*/
public enum ReferenceStrength {
/**
* Hard reference type.
*/
HARD(0),
/**
* Soft reference type.
*/
SOFT(1),
/**
* Weak reference type.
*/
WEAK(2);
/**
* Resolve enum from int.
* @param value the int value
* @return ReferenceType
* @throws IllegalArgumentException if the specified value is invalid.
*/
public static ReferenceStrength resolve(final int value) {
switch (value) {
case 0:
return HARD;
case 1:
return SOFT;
case 2:
return WEAK;
default:
throw new IllegalArgumentException();
}
}
/** Value */
public final int value;
ReferenceStrength(final int value) {
this.value = value;
}
}
/**
* Values implementation.
*/
static class ReferenceValues extends Values {
protected ReferenceValues(final AbstractHashedMap, V> parent) {
super(parent);
}
@Override
public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override
public T[] toArray(final T[] arr) {
// special implementation to handle disappearing values
final List list = new ArrayList<>(size());
forEach(list::add);
return list.toArray(arr);
}
}
/**
* The values iterator.
*/
static class ReferenceValuesIterator extends ReferenceBaseIterator