0

I want to create a cache like so

Cache<String, File> cache = Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .maximumSize(100)
                .build();

That i will populate with a temporary file like so,

File f = File.createTempFile("jobid_", ".json");
FileWriter fileWriter = new FileWriter(f);
fileWriter.write("text values 123");
fileWriter.close();


cache.put("jobid", f);

Now after 1 minute I understand that cache.getIfPresent("jobid") will return null, my question is that is there some way in which I can trigger another task when this entry expires - deleting the temporary file itself.

Any alternative solution works as well.

4

1 回答 1

0

感谢毛茸茸的。

要实现相同的功能,简单地使用removingListener。

对于我的用例:

Cache<String, File> cache = Caffeine.newBuilder()
    .removalListener((String key, File file, RemovalCause cause) -> {
      file.delete();
    })
    .expireAfterWrite(3, TimeUnit.SECONDS)
    .maximumSize(100)
    .build();

解决问题。

于 2021-03-09T13:55:45.583 回答