JAVA菜鸟入门(12) reference variable是气球的线 +JVM中怎么实现

本文通过气球与线的比喻解释了Java中对象引用的工作原理,指出对象引用传递实际上是引用值的复制。介绍了两种JVM实现引用的方式:一种是直接存储对象内存地址,另一种是通过中间层处理,以及这两种方式的优缺点。同时,讨论了对象的锁、等待集合以及垃圾收集器在对象表示中的数据需求。
摘要由CSDN通过智能技术生成

1 如果variable是primitive,那就拷贝原来变量的值到新变量。

2 如果variable是object referece, 那就拷贝原来reference的值到新的变量,所以就有2个reference varibal指向了相同的object.

3. Java passes objects as references and those references are passed by value.

eg. 

// Before the method call
Object x = null;
// Start of method call - parameter copying
Object y = x;
// Body of method call
y = "This is a piece of string.";
// End of method call
System.out.println (x);// 什么也没打印



下面看到一段非常形象的解释:

The balloon analogy

I imagine every object as a helium balloon, every reference as a piece of string, and every variable as something which can hold onto a piece of string. If the reference is a null reference, that's like having a piece of string without anything attached to the end. If it's a reference to a genuine object, it's a piece of string tied onto the balloon representing that object. When a reference is copied (either for variable assignment or as part of a method call) it's as if another piece of string is created attached to whatever the first piece of string is attached to. The actual piece of string the variable (if any) is holding onto doesn't go anywhere - it's only copied.

This analogy also explains garbage collection (apart from the java.lang.ref API, which does "odd" things :) - a balloon floats away unless it is tethered down to something. The balloons can have further holders on them (instance variables), but just because two balloons are holding onto each other doesn't stop them from floating away. (Cyclic references are collected.) Any balloon representing an object which is in the middle of having a method invoked is tethered to the JVM. (Apologies for not being able to phrase that more succinctly - all I mean is that anything in an active thread's stack isn't garbage collected.)


那么,到底object的reference variable 是一种什么样的东西呢?有人说这不是C++里面的pointer,有人说其实本质上是的,只是换了个名字。

搜到一篇非常好的blog   Java Virtual Machine,说明reference variable 到底是怎样实现的,取决于java virtual machine 的内在机制的具体实现。

第一种实现方式是,在reference中存放object的内存地址,这样中间只需一次中转就可以找到这个object, 但是这样的话,接下来当java virtual machine回收碎片内存的时候,就会很麻烦,你必须更新同一个ojbect的所有相关的referece.

第二种实现方式是,中间增加一层,让reference varibal指向一个中间变量,让这个中间变量指向object 的内存地址,增加了额外的空间来换取方便。

这两种方式的具体解释抄来如下:


Object Representation

The Java virtual machine specification is silent on how objects should be represented on the heap. Object representation--an integral aspect of the overall design of the heap and garbage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值