我有一个包含静态集合的类,该集合可以在所有线程中使用。它充当缓存。首次从数据库中加载它时,它永远不会改变。但是,在极少数情况下,我们必须清除此缓存。当前执行此操作的方法是重新启动服务器。我想实现一个明确的缓存方法。做这个的最好方式是什么?
示例类:
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();
}
但是我需要确保它在所有线程中都将其清除并且不会破坏任何内容。
最佳答案
针对OP的后续评论:
使用syncedList是否会对性能造成影响?这是一个庞大的架构的核心。
是的,对性能有很大影响。您必须对其进行测量以找出多少。一方面,即使大多数操作都是只读的,将每个操作同步到Department
集合也可能导致大量争用。为了提高性能的线程安全性,请考虑以下内容:
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class DepartmentRepository
{
private static final ReentrantReadWriteLock lock =
new ReentrantReadWriteLock(true);
private static Collection<Department> departments = null;
public Collection<Department> getAllDepartments()
{
Lock read = lock.readLock();
read.lock();
try {
/* Check whether the departments are loaded. */
if (departments == null) {
/* If not loaded, release read-lock and acquire write-lock. */
read.unlock();
Lock write = lock.writeLock();
write.lock();
try {
/* Recheck condition for updates by another thread. */
if (departments == null) {
Collection<Department> tmp = ...; // Initialize.
departments = Collections.unmodifiableCollection(tmp);
}
/* Downgrade from write-lock to read-lock. */
read.lock();
}
finally {
write.unlock();
}
}
return departments;
}
finally {
read.unlock();
}
}
public void clearCache()
{
Lock write = lock.writeLock();
write.lock();
try {
departments = null;
}
finally {
write.unlock();
}
}
}
是的,很乱。线程之间很难共享数据。
关于java - Java中的对象锁定,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1375999/