本文介绍了java cache hashmap每日到期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 HashMap< String,String> ,每天午夜,缓存都会过期。

I would like to have a HashMap<String, String>, that every day at midnight, the cache will expire.

请注意它是J2EE解决方案,因此多个线程可以访问它。

Please note that it's J2EE solution so multiple threads can access it.

在Java中实现它的最佳方法是什么?

What is the best way to implement it in Java?

推荐答案

虽然其他建议可以用来计算到期时间,但重要的是要注意:

Although the other suggestions can work to time the expiration, it is important to note that :

哈希表的到期可以懒惰地完成

即没有任何监控线程!

i.e. without any monitor threads !

实施到期的最简单方法如下:

1) 扩展哈希映射,并在构造函数中创建一个本地的nextMidtime(Long)变量,初始化为System.currentTime ....这将设置为等于下午夜时间,以毫秒为单位...

1) Extend hash map, and create a local nextMidtime (Long) variable, initialized to System.currentTime....in the constructor. This will be set equal to the Next midnight time, in milliseconds...

2)将以下代码段添加到第一行containsKey和get方法(或任何其他负责确保数据不陈旧的方法)如下:

2) Add the following snippet to the first line of the the "containsKey" and "get" methods (or any other methods which are responsible for ensuring that data is not stale) as follows :

if (currentTime> nextMidTime)
      this.clear();
      //Lets assume there is a getNextMidnight method which tells us the nearest midnight time after a given time stamp.  
      nextMidTime=getNextMidnight(System.currentTimeInMilliseconds);

这篇关于java cache hashmap每日到期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:38