你更新時間碼應該在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