【发布时间】:2015-07-15 03:56:44
【问题描述】:
我有以下物品:
// this class is immutable, acts like container for several properties.
public class MyDataAddOps{
private final boolean isActive;
private final Map<String,Object> additionalProps;
public MyDataAddOps(boolean isActive, Map<String,Object> additionalProps){
this.isActive = isActive;
this.additionalProps = additionalProps;
}
public boolean isActive(){return isActive;}
public Map<String,Object> getAdditionalProps(){ return additionalProps;}
}
// this class acts as "spring" bean that calls load on construction,
// and then another scheduler bean calls the load per some cron expression (once a minute for example)
public class MyDataAddOpsService{
private MyDataAddOps data;
// this method will be executed periodically outside
// via some spring quartz for example
// the quartz is not re-entrant
public void load(){
// opens some defined file and returns content string
String fileData = getFileContent();
boolean isActive = getIsActive(fileData);
Map<String, Object> props = getProps(fileData);
data = new MyDataAddOps(isActive, props);
}
// This method is executed by many workers threads inside the application
public boolean isActive(){
return data.isActive();
}
public final Map<String, Object> getProps(){
return data.getAdditionalProps();
}
}
这种方法可能存在竞争条件,一个线程执行isActive(),另一个线程执行load()。虽然它对引用进行操作并且对象状态没有改变。
支持这种并发的最佳解决方案是什么?我想避免方法同步,还有读写锁。
也许是AtomicReference 或volatile?或者最好只返回对数据本身的引用而不使用代理方法?所以根本不需要加锁,所有的使用逻辑都在这个服务之外?
public class MyDataAddOpsService{
private MyDataAddOps data;
public void load(){
....
data = new MyDataAddOps(isActive, props);
}
public MyDataAddOps getData(){
return data;
}
}
【问题讨论】:
-
MyDataAddOps绝对不是一成不变的。您担心线程安全问题是对的,但它们远远超出了您所指出的问题。使这个代码线程安全可能超出了本论坛的范围。
标签: java multithreading concurrency