java 基本數(shù)據(jù)類(lèi)型各種情況下在內(nèi)存中存儲(chǔ)位置?
問(wèn)題描述
問(wèn)題:如何理解《Java編程思想-第四版》P23 中,這個(gè)變量直接存儲(chǔ)“值”,并置于堆棧中,因此更加高效一句中的 “堆棧” 兩字,到底是堆還是棧?情況如下:
class demo { private int var1; // 字段1 private Integer var2; // 字段2 public static void main(String[] args) {int var3 = 0; // 變量1demo obj1 = new demo(); // 實(shí)例1 }}我的理解
參考《Java編程思想-第四版》P23 和 《深入理解Java虛擬機(jī):JVM高級(jí)特性與最佳實(shí)踐 第2版》P39-P43,對(duì)于該 demo
實(shí)例1:存儲(chǔ)在堆內(nèi)存中
變量1:存儲(chǔ)在方法棧中
實(shí)例1中的字段1:存儲(chǔ)在堆中
實(shí)例1中的字段2:存儲(chǔ)在堆中
如果是存儲(chǔ)在堆中的話,何來(lái)高效一說(shuō)?
問(wèn)題解答
回答1:我們不能一概而論的說(shuō),基本類(lèi)型數(shù)據(jù)都是放在棧中的!當(dāng)某個(gè) 類(lèi)實(shí)例 中具有基本類(lèi)型時(shí),基本類(lèi)型就放在堆中!
回答2:內(nèi)存分為堆和棧,這你已經(jīng)知道了。
堆內(nèi)存是屬于JVM的,棧內(nèi)存是屬于方法的,方法結(jié)束了,棧內(nèi)存也就沒(méi)了。
程序運(yùn)行main函數(shù)時(shí),有一個(gè)堆內(nèi)存,一個(gè)main的棧內(nèi)存
int var3 = 0;這個(gè)var3,是放在main函數(shù)的棧內(nèi)存中的,是一個(gè)值。
之后demo obj1 = new demo();main函數(shù)的棧內(nèi)存中有了一個(gè)引用變量,obj1,指向了堆內(nèi)存中new出來(lái)的這個(gè)實(shí)例。
我們?cè)倏炊褍?nèi)存中的這個(gè)實(shí)例,他有2個(gè)字段,他們都是存放在堆中的。
等到main函數(shù)運(yùn)行結(jié)束時(shí),假如還有別的線程在運(yùn)行,JVM還沒(méi)有結(jié)束,此時(shí),main函數(shù)的棧內(nèi)存被清除,var3,不在了,obj1這個(gè)引用變量也不在了,但是堆內(nèi)存中的那個(gè)實(shí)例依然在,如果沒(méi)有別的引用變量 指向它 ,那么它將在稍后被清除。
回答3:是翻譯錯(cuò)誤,原文中用的是stack,即棧,而不是堆棧。以下是原文:
Special case: primitive typesOne group of types, which you’ll use quite often in your programming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap. For these types Java falls back on the approach taken by C and C++. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and it’s placed on the stack, so it’s much more efficient.
回答4:p22,堆棧指的是stack,堆指的是heap
相關(guān)文章:
1. mac里的docker如何命令行開(kāi)啟呢?2. 為什么我ping不通我的docker容器呢???3. nignx - docker內(nèi)nginx 80端口被占用4. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””5. docker容器呢SSH為什么連不通呢?6. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問(wèn)題7. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問(wèn)題。8. javascript - 最近用echarts做統(tǒng)計(jì)圖時(shí)遇到兩個(gè)問(wèn)題!!9. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個(gè)是怎么回事????10. docker gitlab 如何git clone?

網(wǎng)公網(wǎng)安備