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.
Thanks to fluffy.
To implement the same, simple use the removalListener.
For my use case:
Cache<String, File> cache = Caffeine.newBuilder()
.removalListener((String key, File file, RemovalCause cause) -> {
file.delete();
})
.expireAfterWrite(3, TimeUnit.SECONDS)
.maximumSize(100)
.build();
solves the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.