2

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.

1 Answers1

2

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.

Ben Manes
  • 9,178
  • 3
  • 35
  • 39