java類的屬性 java哪個關(guān)鍵字可以對對象加互斥鎖?
java哪個關(guān)鍵字可以對對象加互斥鎖?首先,Java中synchronized可以實現(xiàn)對對象加互斥鎖。其次,我們來聊一聊synchronized互斥鎖的實現(xiàn)原理。Java虛擬機中,synchroniz
java哪個關(guān)鍵字可以對對象加互斥鎖?
首先,Java中synchronized可以實現(xiàn)對對象加互斥鎖。
其次,我們來聊一聊synchronized互斥鎖的實現(xiàn)原理。Java虛擬機中,synchronized支持的同步方法和同步語句都是使用monitor來實現(xiàn)的。每個對象都與一個monitor相關(guān)聯(lián),當一個線程執(zhí)行到一個monitor監(jiān)視下的代碼塊中的第一個指令時,該線程必須在引用的對象上獲得一個鎖,這個鎖是monitor實現(xiàn)的。在HotSpot虛擬機中,monitor是由ObjectMonitor實現(xiàn),使用C 編寫實現(xiàn),具體代碼在HotSpot虛擬機源碼ObjectMonitor.hpp文件中。
查看源碼會發(fā)現(xiàn),主要的屬性有_count(記錄該線程獲取鎖的次數(shù))、_recursions(鎖的重入次數(shù))、_owner(指向持有ObjectMonitor對象的線程)、_WaitSet(處于wait狀態(tài)的線程集合)、_EntryList(處于等待鎖block狀態(tài)的線程隊列)。
當并發(fā)線程執(zhí)行synchronized修飾的方法或語句塊時,先進入_EntryList中,當某個線程獲取到對象的monitor后,把monitor對象中的_owner變量設(shè)置為當前線程,同時monitor對象中的計數(shù)器_count加1,當前線程獲取同步鎖成功。
當synchronized修飾的方法或語句塊中的線程調(diào)用wait()方法時,當前線程將釋放持有的monitor對象,monitor對象中的_owner變量賦值為null,同時,monitor對象中的_count值減1,然后當前線程進入_WaitSet集合中等待被喚醒。
java synchronized鎖對象,當對象引用是null的時候,鎖的是什么?
謝邀!
Java語言規(guī)范中明確指出如果鎖住的對象是null,則會NullPointerException,規(guī)范內(nèi)容如下:
The type of Expression must be a reference type, or a compile-time error occurs. A synchronized statement is executed by first evaluating the Expression. Then: If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason. Otherwise, if the value of the Expression is null, a NullPointerException is thrown.