我有一个类,其中包含一个可跨所有线程使用的静态集合。它充当缓存。当它第一次从数据库中加载时,它应该永远不会改变。但是,在极少数情况下,我们必须清除此缓存。当前执行此操作的方法是重新启动服务器。我想实现一个清除缓存的方法。执行此操作的最佳方法是什么?
示例类:
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
}
我想添加一个如下所示的方法:
public void clearCache() {
departments.clear();
}
但我需要确保它在所有线程中清除它并且不会破坏任何东西。
最佳答案
老实说,最简单的方法就是:
private static Collection<Department> departments = Collections.synchronizedList(new ArrayList<Department>());
而不是你拥有它的方式。
另一种方式是:
public void clearCache() {
synchronized(departments) {
departments.clear();
}
}
假设您正在同步访问此集合的方法中的其他线程。
关于java - Java 中的对象锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1375999/