【发布时间】:2015-09-22 11:19:53
【问题描述】:
public class ActionForm {
private Account temporaryAccount = null;
private Document document;
/**
* Save document from another thread that do not have a SecurityContext
*/
public void saveByAccount(Account account) {
this.temporaryAccount = account;
save();
this.temporaryAccount = null;
}
/**
* Save document to DB.
* I can not change the signature of this method.
*/
public synchronized void save() {
//get an account from shared variable or from SecurityContext
Account account = null;
Account temporaryAccount = this.temporaryAccount;
if (temporaryAccount == null) {
account = SecurityContextWrapper.getAccount();
} else {
account = temporaryAccount;
}
//save in DB
saveDocumentInDB(account, document);
}
}
线程类型 1:用户可以点击“保存”按钮,在这种情况下方法 save() 将直接调用。我从 SecurityContext 获得帐户。
线程类型2:用户启动后台进程。我保存他/她的帐户,然后开始新线程:
final Account account = SecurityContextWrapper.getAccount();
new Thread(new Runnable() {
public void run() {
...//do smth
saveByAccount(account);
}
}).start();
问题:变量 this.temporaryAccount 可以更改 - 在调用 saveByAccount() 和 save() 之间。 您知道同步这些方法的正确方法吗?
【问题讨论】:
-
为什么要在类级别存储一个临时变量,我们不能在不同的方法调用之间共享帐户,例如 save(account);从 saveByAccount 中
-
@Akash Yadav 方法 save() 在我们项目的很多地方使用。更改签名是个问题。
-
添加一个包含实际逻辑的新方法
save( Account a ),并从save()等调用save(temporaryAccount)。 -
除了将帐户作为参数传递之外,您还可以尝试使访问
temporaryAccount的每个方法或代码块同步(代码块使用synchronized(this))。 -
既然temporaryAccount 是一个私有成员,只能通过save() 设置,为什么不让save 方法同步,你应该好好去
标签: java multithreading synchronized java.util.concurrent