我正在閱讀 tomcat 的源代碼,我注意到一些奇怪的地方org.apache.catalina.webresources.CachedResource:
@Override
public long getLastModified() {
Long cachedLastModified = this.cachedLastModified;
if (cachedLastModified == null) {
cachedLastModified =
Long.valueOf(webResource.getLastModified());
this.cachedLastModified = cachedLastModified;
}
return cachedLastModified.longValue();
}
如果我將其替換為:
@Override
public long getLastModified() {
if (this.cachedLastModified == null) {
this.cachedLastModified =
Long.valueOf(webResource.getLastModified());
}
return this.cachedLastModified.longValue();
}
有幾個這樣的功能。我不明白它是這樣寫的。
uj5u.com熱心網友回復:
我寫那段代碼已經快 10 年了。
出于執行緒安全的原因,它是這樣寫的。快取條目過期時的原始代碼集this.cachedLastModified(以及明顯的其他欄位) 。nullgetter 是這樣撰寫的,以避免 NPE。
隨后的重構改變了快取過期的實作方式,這消除了執行緒安全問題,但相關的保護并未從 getter 中移除。
可以重構 getter 以洗掉現在不必要的保護并簡化代碼。
您可以在svn log中查看原始代碼以及快取到期實作的更改方式。
通常,如果您在 Tomcat 代碼庫中的方法開頭看到一個或多個欄位的副本,則原因幾乎總是為了解決執行緒安全問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/493012.html
標籤:雄猫
