blob: 3a445562ef7e7fc16e3539050c3655891e3cd113 [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
2* Copyright 2011, Big Switch Networks, Inc.
3* Originally created by David Erickson, Stanford University
4*
5* Licensed under the Apache License, Version 2.0 (the "License"); you may
6* not use this file except in compliance with the License. You may obtain
7* a copy of the License at
8*
9* http://www.apache.org/licenses/LICENSE-2.0
10*
11* Unless required by applicable law or agreed to in writing, software
12* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14* License for the specific language governing permissions and limitations
15* under the License.
16**/
17
18package net.floodlightcontroller.util;
19
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080020import java.util.concurrent.ConcurrentMap;
21
Jonathan Harta99ec672014-04-03 11:30:34 -070022import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
23
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080024/**
25 * The key is any object/hash-code
26 * The value is time-stamp in milliseconds
27 * The time interval denotes the interval for which the entry should remain in the hashmap.
28 * If an entry is present in the Linkedhashmap, it does not mean that it's valid (recently seen)
29 *
30 * @param <K> Type of the values in this cache
31 */
32public class TimedCache<K> {
33 private final long timeoutInterval; //specified in milliseconds.
34 private ConcurrentMap<K, Long> cache;
35
36 /**
37 *
38 * @param capacity the maximum number of entries in the cache before the
39 * oldest entry is evicted.
40 * @param timeToLive specified in milliseconds
41 */
42 public TimedCache(int capacity, int timeToLive) {
43 cache = new ConcurrentLinkedHashMap.Builder<K, Long>()
44 .maximumWeightedCapacity(capacity)
45 .build();
46 this.timeoutInterval = timeToLive;
47 }
48
49 public long getTimeoutInterval() {
50 return this.timeoutInterval;
51 }
52
53 /**
54 * Always try to update the cache and set the last-seen value for this key.
55 *
56 * Return true, if a valid existing field was updated, else return false.
57 * (note: if multiple threads update simultaneously, one of them will succeed,
58 * other wills return false)
59 *
60 * @param key
61 * @return boolean
62 */
63 public boolean update(K key)
64 {
65 Long curr = new Long(System.currentTimeMillis());
66 Long prev = cache.putIfAbsent(key, curr);
67
68 if (prev == null) {
69 return false;
70 }
71
72 if (curr - prev > this.timeoutInterval) {
73 if (cache.replace(key, prev, curr)) {
74 return false;
75 }
76 }
77
78 return true;
79 }
80}