Coverage Summary for Class: RskCustomCache (co.rsk.util)

Class Method, % Line, %
RskCustomCache 0% (0/7) 0% (0/26)
RskCustomCache$1 0% (0/2) 0% (0/2)
Total 0% (0/9) 0% (0/28)


1 /* 2  * This file is part of RskJ 3  * Copyright (C) 2017 RSK Labs Ltd. 4  * 5  * This program is free software: you can redistribute it and/or modify 6  * it under the terms of the GNU Lesser 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. 9  * 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 Lesser General Public License for more details. 14  * 15  * You should have received a copy of the GNU Lesser General Public License 16  * along with this program. If not, see <http://www.gnu.org/licenses/>. 17  */ 18  19 package co.rsk.util; 20  21 import java.util.Iterator; 22 import java.util.Map; 23 import java.util.concurrent.*; 24  25 /** 26  * Created by mario on 09/09/2016. 27  */ 28 public class RskCustomCache<K, T> { 29  30  private Long timeToLive; 31  32  private Map<K, CacheElement<T>> cache = new ConcurrentHashMap<>(); 33  34  private ScheduledExecutorService cacheTimer; 35  36  public RskCustomCache(Long timeToLive) { 37  this.timeToLive = timeToLive; 38  39  cacheTimer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { 40  public Thread newThread(Runnable r) { 41  return new Thread(r, "BlockHeaderCacheTimer"); 42  } 43  }); 44  } 45  46  public void start() { 47  cacheTimer.scheduleAtFixedRate(this::cleanUp, this.timeToLive, this.timeToLive, TimeUnit.MILLISECONDS); 48  } 49  50  public void stop() { 51  cacheTimer.shutdown(); 52  } 53  54  public void remove(K key) { 55  this.cache.remove(key); 56  } 57  58  public void put(K key, T data) { 59  this.cache.put(key, new CacheElement<T>(data, this.timeToLive)); 60  } 61  62  public T get(K key) { 63  T ret = null; 64  CacheElement<T> element = this.cache.get(key); 65  if(element != null) { 66  element.updateLastAccess(); 67  ret = element.value(); 68  } 69  return ret; 70  } 71  72  73  private void cleanUp() { 74  Iterator<Map.Entry<K, CacheElement<T>>> iter = this.cache.entrySet().iterator(); 75  while (iter.hasNext()) { 76  Map.Entry<K, CacheElement<T>> entry = iter.next(); 77  if(entry.getValue().hasExpired()){ 78  iter.remove(); 79  } 80  } 81  } 82 }