I have a class which contains a static collection that can be used across all threads. It acts as a cache. When it is first loaded from the database, it is supposed to never change. However, in rare cases, we have to clear this cache. The current way to do this is to restart the server. I want to implement a clear cache method. What is the best way to do this?
Example class:
public class DepartmentRepository {
private static Collection<Department> departments = new ArrayList<Department>();
public synchronized Collection<Department> getAllDepartments() {
if (departments.isEmpty()) {
//do database lookup
}
return departments;
}
//more methods excluded
}
I want to add a method that looks like this:
public void clearCache() {
departments.clear();
}
But I need to make sure it clears it across all threads and doesn’t break anything.
In response to a follow-up comment by the OP:
Yes, there is a performance hit. You’d have to measure it to find out how much. For one thing, synchronizing every operation to the
Departmentcollection might result in a lot of contention even when most of the operations are read-only. For thread safety with performance, consider something like this:Yes, it’s messy. Sharing data between threads is hard.