sonar報錯volatile

問題發生

原先代碼以下:git

//認證受權碼
private static volatile String AUTHORIZATION_CODE = "init";

git push 以後,sonar認爲這是個bug檢測報告截圖以下: sonar報錯內容數組

分析排查

解釋說明:緩存

Marking an array volatile means that the array itself will always be read fresh and never thread cached, but the items in the array will not be. Similarly, marking a mutable object field volatile means the object reference is volatile but the object itself is not, and other threads may not see updates to the object state.安全

This can be salvaged with arrays by using the relevant AtomicArray class, such as AtomicIntegerArray, instead. For mutable objects, the volatile should be removed, and some other method should be used to ensure thread-safety, such as synchronization, or ThreadLocal storage.搜索引擎


中文翻譯以下:線程

標記數組volatile意味着數組自己將始終被新鮮讀取而且永遠不會被線程緩存,但數組中的項目將不會。 相似地,標記可變對象字段volatile表示對象引用是易失性但對象自己不是,而且其餘線程可能看不到對象狀態的更新。翻譯

這能夠經過使用相關的AtomicArray類(例如AtomicIntegerArray)來修復數組。 對於可變對象,應該刪除volatile,而且應該使用其餘一些方法來確保線程安全,例如同步或ThreadLocal存儲。code

從搜索引擎上尋找答案,獲得部分解釋說明以下:對象

volatile關鍵字對於基本類型的修改能夠在隨後對多個線程的讀保持一致, 可是對於引用類型如數組,實體bean,僅僅保證引用的可見性,但並不保證引用內容的可見性。blog

即便使用volatile關鍵字修飾string,也不能保證修改後的數據會當即對其餘的多個線程保持一致

解決問題

//認證受權碼
private static AtomicReference<String> ATOMIC_AUTHORIZATION_CODE = 
	new AtomicReference<>();

其賦值與取值,則採用set()、get() 方法來完成。

改動後從新git push 以後,sonar中的bug消除。問題解決

相關文章
相關標籤/搜索