Presume I have the following (pseudo) code:
class Cache {
Entry addIfMissing(String data) {
// omitted for brevity
}
void evictOldEntries() {
// omitted for brevity
}
}
class Program {
private Cache cache = new Cache();
doWork() { // called from multiple threads
var entry = cache.addIfMissing("omitted for brevity");
// work with entry
}
static {
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
cache.evictOldEntries();
}, 10, 10, TimeUnit.MINUTES);
}
}
I want to make sure while the evictOldEntries
method is running all the other threads in the program have to wait for it to be done.
Which synchronization mechanism would be appropriate in such a scenario?