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 javax.annotation.CheckForNull;
022import org.checkerframework.checker.nullness.qual.Nullable;
023
024/**
025 * A notification of the removal of a single entry. The key and/or value may be null if they were
026 * already garbage collected.
027 *
028 * <p>Like other {@code Entry} instances associated with {@code CacheBuilder}, this class holds
029 * strong references to the key and value, regardless of the type of references the cache may be
030 * using.
031 *
032 * @author Charles Fry
033 * @since 10.0
034 */
035@GwtCompatible
036@ElementTypesAreNonnullByDefault
037public final class RemovalNotification<K, V>
038    extends SimpleImmutableEntry<@Nullable K, @Nullable V> {
039  private final RemovalCause cause;
040
041  /**
042   * Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with
043   * the given {@code cause} for the removal. The {@code key} and/or {@code value} may be {@code
044   * null} if they were already garbage collected.
045   *
046   * @since 19.0
047   */
048  public static <K, V> RemovalNotification<K, V> create(
049      @CheckForNull K key, @CheckForNull V value, RemovalCause cause) {
050    return new RemovalNotification(key, value, cause);
051  }
052
053  private RemovalNotification(@CheckForNull K key, @CheckForNull V value, RemovalCause cause) {
054    super(key, value);
055    this.cause = checkNotNull(cause);
056  }
057
058  /** Returns the cause for which the entry was removed. */
059  public RemovalCause getCause() {
060    return cause;
061  }
062
063  /**
064   * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
065   * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
066   */
067  public boolean wasEvicted() {
068    return cause.wasEvicted();
069  }
070
071  private static final long serialVersionUID = 0;
072}