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.