如果我有一个下面定义的 Java 类,它通过依赖注入注入到我的 Web 应用程序中:
public AccountDao
{
private NamedParameterJdbcTemplate njt;
private List<Account> accounts;
public AccountDao(Datasource ds)
{
this.njt = new NamedParameterJdbcTemplate(ds);
refreshAccounts();
}
/*called at creation, and then via API calls to inform service new users have
been added to the database by a separate program*/
public void refreshAccounts()
{
this.accounts = /*call to database to get list of accounts*/
}
//called by every request to web service
public boolean isActiveAccount(String accountId)
{
Account a = map.get(accountId);
return a == null ? false : a.isActive();
}
}
我担心线程安全。Spring 框架是否不处理一个请求正在从列表中读取并且当前正在被另一个请求更新的情况?我之前在其他应用程序中使用过读/写锁,但我以前从未想过像上面这样的情况。
我打算将 bean 用作单例,这样我就可以减少数据库负载。
顺便说一句,这是对以下问题的跟进:
编辑:
那么这样的代码会解决这个问题吗:
/*called at creation, and then via API calls to inform service new users have
been added to the database by a separate program*/
public void refreshAccounts()
{
//java.util.concurrent.locks.Lock
final Lock w = lock.writeLock();
w.lock();
try{
this.accounts = /*call to database to get list of accounts*/
}
finally{
w.unlock();
}
}
//called by every request to web service
public boolean isActiveAccount(String accountId)
{
final Lock r = lock.readLock();
r.lock();
try{
Account a = map.get(accountId);
}
finally{
r.unlock();
}
return a == null ? false : a.isActive();
}