Drupal: bez dědičnosti, implementujeme rovnou rozhraní (nelze dědit).
3 * see AUTHORS for the list of contributors
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package org.sonews.util;
21 import java.util.HashMap;
22 import java.util.HashSet;
25 import java.util.concurrent.ConcurrentHashMap;
28 * Implementation of a Map that will loose its stored values after a
29 * configurable amount of time.
30 * This class may be used to cache config values for example.
31 * @author Christian Lins
34 public class TimeoutMap<K, V> extends ConcurrentHashMap<K, V>
37 private static final long serialVersionUID = 453453467700345L;
38 private int timeout = 60000; // 60 sec
39 private transient Map<K, Long> timeoutMap = new HashMap<K, Long>();
43 * @param timeout Timeout in milliseconds
45 public TimeoutMap(final int timeout)
47 this.timeout = timeout;
51 * Uses default timeout (60 sec).
60 * @return true if key is still valid.
62 protected boolean checkTimeOut(Object key)
64 synchronized (this.timeoutMap) {
65 if (this.timeoutMap.containsKey(key)) {
66 long keytime = this.timeoutMap.get(key);
67 if ((System.currentTimeMillis() - keytime) < this.timeout) {
80 public boolean containsKey(Object key)
82 return checkTimeOut(key);
86 public synchronized V get(Object key)
88 if (checkTimeOut(key)) {
89 return super.get(key);
96 public V put(K key, V value)
98 synchronized (this.timeoutMap) {
100 this.timeoutMap.put(key, System.currentTimeMillis());
101 return super.put(key, value);
110 public V remove(Object arg0)
112 synchronized (this.timeoutMap) {
113 this.timeoutMap.remove(arg0);
114 V val = super.remove(arg0);
119 protected void removeStaleKeys()
121 synchronized (this.timeoutMap) {
122 Set<Object> keySet = new HashSet<Object>(this.timeoutMap.keySet());
123 for (Object key : keySet) {
124 // The key/value is removed by the checkTimeOut() method if true