考慮下面的代碼:同步使用條件?我怎樣才能使這個代碼的性能和線程安全?
public class SomeClass {
private boolean shouldBlock = false;
private Object resource;
public void handleDrawRequest(Canvas canvas) {
if (!shouldBlock && resource == null)
{
shouldBlock = true;
loadTheResource(); //which takes awhile
shouldBlock = false;
}
else if (shouldBlock && resrouce == null)
{
return; //another thread is taking care of the loading of the resource
//and its not ready yet, so just ignore this request
}
drawResourceOn(canvas);
}
}
我怎樣才能使此代碼線程安全的?我試圖完成的是隻有一個線程來加載資源,同時任何其他線程試圖同時訪問此代碼將被丟棄(例如,遵循'else if'邏輯)直到資源被加載。可能有很多線程試圖同時訪問這些代碼,我不想同步整個方法並且有一堆線程堆積起來。
不確定你是否需要資源'volatile'。 – OldCurmudgeon 2012-02-12 01:51:02
看起來不錯,簡單。但是,加載資源可能會失敗,將資源留空,我希望將來的線程能夠重新加載資源。 AtomicReference可以幫助嗎?或者就像在loadTheResource()之後添加loadingResource.compareAndSet(true,false)一樣簡單? –
2012-02-12 08:31:35
@Chris,如果加載資源失敗,AtomicBoolean可以重置爲false。 – Scorpion 2012-02-12 10:32:39