tha*_*guy 8 java spring multithreading
如果我在下面定义了一个通过依赖注入在我的Web应用程序中注入的Java类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我担心线程安全.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();
}
Run Code Online (Sandbox Code Playgroud)
Lan*_*Lan 13
关于单例bean的多线程行为,Spring框架没有做任何事情.开发人员有责任处理单例bean的并发问题和线程安全问题.
我建议阅读下面的文章:Spring Singleton,Request,Session Beans和Thread Safety
| 归档时间: |
|
| 查看次数: |
36249 次 |
| 最近记录: |