I am populating my guava cache from multiple threads by calling add
method. Now from the background thread which runs every 30 seconds, I want to send whatever is there in the cache to sendToDB
method atomically?
Below is my code:
public class Example {
private final ScheduledExecutorService executorService = Executors
.newSingleThreadScheduledExecutor();
private final Cache<Integer, List<Process>> cache = CacheBuilder.newBuilder().maximumSize(100000)
.removalListener(RemovalListeners.asynchronous(new CustomRemovalListener(), executorService))
.build();
private static class Holder {
private static final Example INSTANCE = new Example();
}
public static Example getInstance() {
return Holder.INSTANCE;
}
private Example() {
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// is this the right way to send cache map?
sendToDB(cache.asMap());
}
}, 0, 30, SECONDS);
}
// this method will be called from multiple threads
public void add(final int id, final Process process) {
// add id and process into cache
}
// this will only be called from single background thread
private void sendToDB(ConcurrentMap<Integer, List<Process>> holder) {
// use holder here
}
}
Is this the right way to send cache
map to my sendToDB
method? Basically I want to send all the entries that are there in the cache for that 30 seconds and empty the cache out. After that my cache will get populated again in the next 30 seconds and then do the same process?
I think using cache.asMap()
might not be the right way since it doesn't empty the cache out so it will reflect all the changes happening on the cache in my sendToDB
method as well?
asMap
returns a copy of the content if I remember well, just 1/ asMap, clean, then call your method – user180100add()
method (at least an outline)? Are you using Java 8? Do you have to clear the map, or could you leave the keys and reset the values? – shmosel