gpt4 book ai didi

java - 一定时间后销毁java中的对象

转载 作者:行者123 更新时间:2023-12-01 13:35:11 25 4
gpt4 key购买 nike

  • TTLCache 是一种特殊类型的缓存,用户可以将对象放入缓存中并保留生存时间
  • 对象应在其生存时间后自动过期
  • 这是缓存的测试代码
  • 如何在一定时间后销毁对象?

这是 stub :

public static void testTTLCache() throws Exception {      
TTLCache cache = null; /* replace with new YourClass() */
cache.put("key1", "value1", 5);
cache.put("key2", "value2", 10);

System.out.println(cache.get("key1")); // should print value1
System.out.println(cache.get("key2")); // should print value2
Thread.sleep(1000*6);
System.out.println(cache.get("key1")); // should print NULL
System.out.println(cache.get("key2")); // should print value2
Thread.sleep(1000*6);
System.out.println(cache.get("key1")); // should print NULL
System.out.println(cache.get("key2")); // should print NULL
}

这里是根据我的需求实现的接口(interface),当然如果你需要可以添加其他方法

public interface TTLCache {

/**
* @param key - The key to associate with the cache
* @param value - The actual value to store in the cache
* @param timeToLiveSeconds - The time to live for this object in the cache
*/
public void put(String key, Object value, long timeToLiveSeconds);

/**
* Returns the Object in the cache that is associated with passed key, or NULL if
* no value is associated with the key
* @param key - The key associated with the value to retrieve
*
*/
public Object get(String key);

}

最佳答案

首先,您必须区分在过期时间后从缓存中删除项目和真正销毁它。

在 Java 中,您无法控制对象何时被有效销毁,但您可以使对象符合销毁和释放条件(通过删除代码中对它们的任何引用)。因此,如果通过 destroying 你的意思是避免返回过期的值那么你没问题,如果通过销毁你的意思是释放它那么你就不走运了,因为你唯一能做的就是删除所有引用并等待垃圾收集器完成它的工作。

我看到了两种可能的 TTLCache 实现解决方案:

  • 保持一个管理对象过期的运行线程,当你添加一个新对象时保存它的时间戳和持续时间,每个线程检查是否有过期的对象并将它们从缓存中删除
  • 一种更懒惰的方法:不使用线程,仅当您尝试获取对象时才检查它是否仍然有效。

例如:

void get(String key) {
if (key is expired) {
remove key,value from cache;
return null;
}
else
return value for key;
}

关于java - 一定时间后销毁java中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20827166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com