001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.cache;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import java.util.AbstractMap.SimpleImmutableEntry;
021import org.checkerframework.checker.nullness.compatqual.NullableDecl;
022
023/**
024 * A notification of the removal of a single entry. The key and/or value may be null if they were
025 * already garbage collected.
026 *
027 * <p>Like other {@code Entry} instances associated with {@code CacheBuilder}, this class holds
028 * strong references to the key and value, regardless of the type of references the cache may be
029 * using.
030 *
031 * @author Charles Fry
032 * @since 10.0
033 */
034@GwtCompatible
035public final class RemovalNotification<K, V> extends SimpleImmutableEntry<K, V> {
036  private final RemovalCause cause;
037
038  /**
039   * Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with
040   * the given {@code cause} for the removal. The {@code key} and/or {@code value} may be {@code
041   * null} if they were already garbage collected.
042   *
043   * @since 19.0
044   */
045  public static <K, V> RemovalNotification<K, V> create(
046      @NullableDecl K key, @NullableDecl V value, RemovalCause cause) {
047    return new RemovalNotification(key, value, cause);
048  }
049
050  private RemovalNotification(@NullableDecl K key, @NullableDecl V value, RemovalCause cause) {
051    super(key, value);
052    this.cause = checkNotNull(cause);
053  }
054
055  /** Returns the cause for which the entry was removed. */
056  public RemovalCause getCause() {
057    return cause;
058  }
059
060  /**
061   * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
062   * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
063   */
064  public boolean wasEvicted() {
065    return cause.wasEvicted();
066  }
067
068  private static final long serialVersionUID = 0;
069}