View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package org.waarp.common.lru;
21  
22  import java.lang.ref.SoftReference;
23  
24  /**
25   * Cache entry which uses SoftReference to store value
26   *
27   * @author Damian Momot
28   */
29  class SoftReferenceCacheEntry<V> implements InterfaceLruCacheEntry<V> {
30  
31    private final SoftReference<V> valueReference;
32  
33    private long expirationTime;
34  
35    /**
36     * Creates LruCacheEntry with desired ttl
37     *
38     * @param value
39     * @param ttl time to live in milliseconds
40     *
41     * @throws IllegalArgumentException if ttl is not positive
42     */
43    SoftReferenceCacheEntry(final V value, final long ttl) {
44      if (ttl <= 0) {
45        throw new IllegalArgumentException("ttl must be positive");
46      }
47  
48      valueReference = new SoftReference<V>(value);
49      expirationTime = System.currentTimeMillis() + ttl;
50    }
51  
52    /**
53     * Returns value if entry is valid, null otherwise.
54     * <p>
55     * Entry is invalid if SoftReference is cleared or entry has expired
56     *
57     * @return value if entry is valid
58     */
59    @Override
60    public final V getValue() {
61      V value = null;
62  
63      // check expiration time
64      if (System.currentTimeMillis() <= expirationTime) {
65        value = valueReference.get();
66      }
67  
68      return value;
69    }
70  
71    @Override
72    public final boolean isStillValid(final long timeRef) {
73      return timeRef <= expirationTime;
74    }
75  
76    @Override
77    public final boolean resetTime(final long ttl) {
78      expirationTime = System.currentTimeMillis() + ttl;
79      return true;
80    }
81  }