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.qual.Nullable;
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>
036    extends SimpleImmutableEntry<@Nullable K, @Nullable V> {
037  private final RemovalCause cause;
038
039  /**
040   * Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with
041   * the given {@code cause} for the removal. The {@code key} and/or {@code value} may be {@code
042   * null} if they were already garbage collected.
043   *
044   * @since 19.0
045   */
046  public static <K, V> RemovalNotification<K, V> create(
047      @Nullable K key, @Nullable V value, RemovalCause cause) {
048    return new RemovalNotification<>(key, value, cause);
049  }
050
051  private RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
052    super(key, value);
053    this.cause = checkNotNull(cause);
054  }
055
056  /** Returns the cause for which the entry was removed. */
057  public RemovalCause getCause() {
058    return cause;
059  }
060
061  /**
062   * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
063   * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
064   */
065  public boolean wasEvicted() {
066    return cause.wasEvicted();
067  }
068
069  private static final long serialVersionUID = 0;
070}