你更新时间码应该在synchronized块你的对象
采取写锁,如果有人已经消耗。之前更新操作,并在同一时间的另一个请求到来应该得到的预更新数据后加载/去锁。
再检查一下synchronized关键字在Java中同时选中读写锁机制。这可以帮助你。
˚F根据代码可能会对你有所帮助。
import java.util.Map;
import java.util.HashMap;
public class Test {
boolean isWriteLockTaken;
Map<Integer,String> cachedUsers = new HashMap<Integer,String>();
public static void main(String[] args) throws Exception {
Test t = new Test();
for(int i=0;i<10;i++){
t.updateAndGetUser(1);
}
}
public String updateAndGetUser(Integer id) throws InterruptedException {
if(isWriteLockTaken && !cachedUsers.containsKey(id)){
this.wait();
}
if(!cachedUsers.containsKey(id)){
isWriteLockTaken = true;
synchronized(id){
if(id==1){
// do processing to retrive user
System.out.println("Updating & loading user");
cachedUsers.put(id, "Gaurav");
return "Gaurav";
}
}
isWriteLockTaken = false;
}
System.out.println("returning from cached list, not loading user details as it is already loaded");
return cachedUsers.get(id);
}
}
感谢, 拉夫
查找[在Java并发(http://docs.oracle.com/javase/tutorial/essential/concurrency/)。听起来像[竞态条件](http://en.wikipedia.org/wiki/Race_condition)。 – Qix
你有没有试过。或者它只是实际编码之前的讨论? – Ashish
看到评论后,我尝试添加同步到我的方法,但我没有看到任何更改。 我认为在这种情况下,当向这个方法发出100个请求时,只有一个更新,另外99个请求不这样做。但是当我试图用Jmeter来做时,其中一些更新(超过1),而另一些则不更新。 – ManhDV