java 中的引用类型

ARM CMSIS DAP源码分析(二) 今天分析的是RDDI_DAP_GetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)和RDDI_DAP_SetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)这两个函数。 以RDDI_DAP_GetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)为例,代码如下: 阅读详情
Reference Types In Java 

原文地址:http://mycodefixes.blogspot.jp/2011/09/reference-types-in-java-part-1.html

Lately, I have been learning a thing or two about the JVM internals. And one of the most interesting things that I came to know about was, the existence of different types of references in Java.

To go about it, there are actually 4 kinds of reference types in Java.

  1. Strong references.
  2. Soft references.
  3. Weak references.
  4. Phantom references.

These references are different solely because of the existence of a garbage collection mechanism in the JVM. That is because, the decision of reclaiming memory from the object heap depends not only on the fact that there are active references to an object, but also on the type of reference to the object.

Lets try to see how each of them differ from one another.




Strong references

As a normal programmer(that is, if you consider programmers to be 'normal'), we are most likely to encounter only the most ubiquitous form of references - Strong references. The name of this reference type should by itself give you an idea of the importance of the reference in the opinion of the garbage collector. Any object with an active strong reference to it, will never be garbage collected(except in rare circumstances, such as cyclical references).

Say, for example, when you create a class Employee, and you create a reference to a new employee object like this
Employee emp = new Employee();
you are actually creating a strong reference. An object to which a reference is created in this way will be eligible for garbage collection only when the reference is to it is pointed to null.
So, if you write this
emp = null;
and there are no more references created to this object until the garbage collector runs again, this object will become eligible for garbage collection, and is most likely to be garbage collected.

So, strong references are pretty simple to understand, probably because most of the code that you commonly write mainly consists of strong references. And we let the smart garbage collector take care of cleaning up the memory for us.

However, there might be cases where you need more control over the lifetime of an object. What if you want to keep some kind of a pool of objects, but still want it to be garbage collected if your JVM is running out of memory? In such cases although you may want a reference to the object most of the time, you are willing to let go of a memory reference for a better JVM performance, when times are crucial. This is where the other kinds of references come into the picture.

The 3 remaining Reference types that I discuss here are subclasses of an abstract class Reference.




Soft references

The soft reference class is used to create a soft reference to an existing object that is already referred to by a strong reference. The actual object on the heap that is being referred to is called the  referent.

In order to create a SoftReference to an object, you first need to create a strong reference to that object and then pass that object as a parameter to the constructor of the SoftReference object, as shown in the code below.
Employee emp = new Employee(); //1
SoftReference<Employee> softRef = new SoftReference<employee>(emp);
In the above code, a few interesting things have happened.

  • In line #1,a (referent)object is created and allocated memory on the heap that represents the Employee object.
  • Again, in line #1, a strong reference is created to the newly created employee object. We call this reference 'emp'.
  • In line #2, a new SoftReference object is created and allocated memory on the heap. This is a special object because it contains an internal reference to the (referent) object passed to it in the constructor, i.e. in our case, the actual Employee object on the heap.
  • Again in line #2, a strong reference is created to the SoftReference object on the heap. We call this reference 'softRef'.


So, in total, we have 2 strong references created. And the object that represents the soft reference, internally holds a reference to the actual employee object.

So what is it that makes soft references useful? Soft references are considered to be a special kind of reference by the garbage collector. Let us assume that at a later point of time, we nullify the 'emp' reference as follows and no new strong references were created to this emp object.
emp = null;

Now lets assume that the garbage collector decides to run at this point of time. What it will see is that the current employee object only has a soft reference pointing to it, and no strong references. The garbage collector may optionally choose to reclaim the memory occupied by the employee object. But what makes soft references even more special is the fact that the garbage collector will always reclaim the memory of objects that have only soft references pointing to them before it throws an OutOfMemory Error. This gives the garbage collector some sort of a last chance to save the life of the JVM.

At any given point of time, if the garbage collector has not yet reclaimed the memory of the actual referent object, you can get a strong reference to the referent via the get method.

Employee resurrectedEmp = softRef.get();


The above code resurrects the employee object in the sense that the garbage collector will not consider it a candidate for garbage collection because it now has a Strong Reference pointing to it.

This makes soft references highly useful in creating object pools, where the size of the pool needs to be dynamic. If you do not know the size of a pool when you begin, or choose not to set a minimum or a maximum size on the object pool, instead you want it to grow dynamically, and at the same time, you want to give the JVM a chance to cleanup unused objects, in that case SoftReferences are a perfect fit.




Weak References

Weak references are even more awesome. Thats because seemingly the garbage collector has no regard for an object that only has a week reference. What that means is that the garbage collector will make it eligible for garbage collection because object only has a week reference pointing to it. Not only is that awesome and useful, but desirable as well in some scenarios.

For example, let  us assume that you need to maintain some metadata related to a user per database connection. In such a case you will be tempted to use a hashmap where you can store the database connection as the key and the user metadata as the value. However, this approach has one drawback. When the database connection has been cleaned up by some other part of the application, then you need to ensure the removal of the connection from the hashmap as well. If you forget to do such a thing, a reference to the connection will remain in the hashmap thereby preventing it from being garbage collected. This means that over a period of time, you are bound to end up with a very large hashmap, a clear indication of a memory leak. And the JVM will eventually spit out a OutOfMemoryError.

So, what do you do in such cases? Oh, of course, Weak referencnes to the rescue!

You can simply create a weak reference to the object, in the same way that we created a soft reference.
DBConnection emp = newEmployee(); //1

WeakReference weakRef = new WeakReference<DBConnection>(emp);


This creates a weak reference to the  DBConnection object. This means that if at any future point in of time during the execution of the program, if the garbage collector detects that the only reference to the actual  DBConnection object is a Weak reference, then it will mark the object for garbage collection.

Weak references are primarily used in conjuction with a WeakHashMap. This is a special kind of hashmap where the keys are all made of weak references. So, in our database example, we could effectively create a weak reference of the Database connection and store it in the WeakHashMap and the metadata of the user as the value in the hashmap. In this way, when the application no longer holds a strong reference to the Database connection, the only reference to the database connection object will be the one that we have via the WeakReference entry in the WeakHashMap. When the garbage collector detects this, it will mark the object for garbage collection. When the object is garbage collected, the entry from the WeakHashMap will be removed. And then, finally, we can all go home and rest in peace.

So, colloquially speaking, this is what the Soft reference and the Weak reference tell us about themselves.

Soft Reference : Hey! I am a soft reference. Ill take your shit as long as the JVM has patience. When it begins running out of patience(i.e. about to throw an OutOfMemoryError), i take no more. Your object will be gone. And then you simply have to create a new object.

Weak Reference : Hey! You know what. I am even cooler than the WeakReference. Coz I wont take your shit at all. The moment you lose me, if the JVM detects that you're no longer around, am gonna punch you in the face and run away! (i.e. Marked for garbage collection). Can you dig it sucka!

As you see, our two awesome friends, Softy and Weaky, certainly have some ego there. But they are pretty useful, at crucial times.

Before I proceed any further, there is one more puny lil thing that you might need to know. Oh! Did i just say 'might'. Oh no.. I meant, you should know. And that is ReferenceQueues. ReferenceQueues are some sort of a queue where the JVM can store objects of type reference once it has decided to take some action on the objects to which they refer.

What I mean to say is, let us suppose you have a weak reference which points to an object in the heap. And that object has been left lonely and desolate by the rest of the application.i.e. No strong references to it. And the garbage collector detects this object during its garbage collection cycle. Since this object only has a weak reference to it, the garbage collector will mark it for garbage collection. But at the same time, it looks if there is a reference queue associated with the weak reference that points to this object. If yes, it puts this weak reference in the reference queue to indicate that the object has been marked for garbage collection. The subtle point to be noted here is that even though the object has been marked for garbage collection, garbage collection may not have happened yet. This may be because the object has a finalize method, which the JVM needs to execute before reclaiming memory.

This also means that you can, but should not,unless deemed necessary, resurrect an object in the finalize method and create a strong reference to it. But when you do that, the weak reference still remains en-queued in the ReferenceQueue. Overriding the finalize method to resurrect an object is a rare case, but since it is one of the options that the JVM supports, it is therefore something that needs to be considered. Nevertheless, when you do such things, its almost equivalent to artificially manipulating the life of an object. That's because the second time when the object becomes eligible for garbage collection, the finalize method wont run, which is a good thing because if you run it again, its simply gonna revive itself. So, practically speaking, an object in the JVM has only one spare life. You get just one medical kit at the max. And thats it. You screw up again, and ur doomed. Your object will be on mars, having a boss fight with the garbage collecting thread of the JVM, which will eventually win, and reclaim the memory of the object.

The same facts about the reference queue hold true for Soft references as well.

In order to associate a weak or a soft reference with a reference queue, you can use the 2 argument constructor as shown below.

Employee emp1 = newEmployee();
Employee emp2 = newEmployee();
 
ReferenceQueue softQueue = newReferenceQueue();
ReferenceQueue weakQueue = newReferenceQueue();
 
SoftReference softRef = newSoftReference(emp1, softQueue);
WeakReference softRef = newWeakReference(emp2, weakQueue);


Now, aint that simple? Yes of course it is.
Then again, you haven't met the Phantom yet, have ya?

The phantom reference is a place where it gets all the more interesting.




Phantom References

Phantom references tell a long tale themselves and its a topic that warrants a blog post of its own. However, in this blog post, ill give a brief idea about what they are. Phantom references are quite similar to Strong and Weak references in the sense that the garbage collector will collect the referent object if the only reference to it is the phantom reference. But that's where the similarity ends. 

What makes Phantom references are unique is the way in which they are used along with a reference queue. A phantom reference is always associated with a references queue during construction time. This is because phantom references are enqueued in the queue only when the the object is about to be garbage collected, after the finalize method(if any) has been executed on it. Calling a get() on the Phantom reference always returns null. And that is quite appropriate because the finalize function has already run on the referent object. So, there should be no 'legal' way of resurrecting the object (resurrecting i.e. creating a strong reference). This may at first seem to make no sense, since, what use is a phantom reference if we cant extract the referent from it? But on giving it a deep thought, you would realize that this is not the reason why phantom references are meant to be useful in the first place. It is the time at which the JVM puts a phantom reference in the reference queue that makes its use so intuitively amazing.

That's something that I will be discussing in more detail in the next post. So stay tuned, because, it might just turn out to be a weird crazy experiment. And of course, its possible that some so called 'laws' will be violated. I am still working on it right now. Ill put it up sooner or later.

So folks, see you on the other side! (Hint : That's what phantom references say too).

Happy Programming :)
Signing Off
Ryan

c#仿热血江湖 Int32_1 = (int) table.Rows[i]["FLD_初级附魂"],Int32_2 = (int) table.Rows[i]["FLD_中级附魂"],Int32_3 = (int) table.Rows[i]["FLD_是否绑定"],Int32_0 = (int) table.Rows[i]["FLD_进化"],Form1.smethod_1(2, "加载百宝阁物品----没有百宝阁数据");Form1.smethod_1(2, "加载物品商店----没有物品数据"); 阅读详情

相关推荐

GNSS - PPP软件 - GAMP 在VS2019/2022下完成调试、跑通程序(超详细!)

WIN32;_DEBUG;_CONSOLE;O_WARNINGS;ENAGLO;ENACMP;ENAGAL;ENAQZS;NFREQ=3。

qq_43381998的博客 8255

并发之java.util.concurrent.atomic原子操作类包

15.JDK1.8的Java.util.concurrent.atomic包小结 14.Java中Atomic包的原理和分析 13.java.util.concurrent.atomic原子操作类包 11.java并发之原子性、可见性、有序性 ===== 15.JDK1.8的Java.util.concurrent.atomic包小结 Atomic意为原子的,JUC包又是...

weixin_30616969的博客 769

Tina Linux WiFi驱动移植避坑指南:以RTL8733bs为例,详解设备树、Kconfig与固件依赖

本文详细解析了在Tina Linux上移植RTL8733bs WiFi驱动的关键步骤与常见问题,涵盖设备树配置、内核依赖、固件加载及启动时序等核心环节。通过实战案例和排查清单,帮助开发者规避SDIO控制器配置、电源管理、GPIO极性等典型陷阱,确保驱动稳定运行。

weixin_29164185的博客 266

JUC源码解析之四---AtomicReference类源码解析

AtomicReference类,顾名思义就是原子的更新应用类型,所有的方法都与AtomicInteger类类似,这里我们也是直接给出源码: /** * An object reference that may be updated atomically. See the {@link * java.util.concurrent.atomic} package specificatio...

qq_22158743的博客 207

一种基于因果干预的少样本学习的故障诊断模型

本文提出CIRNet,一种融合元学习与因果干预的少样本故障诊断框架。针对传统方法易学习伪相关特征的问题,CIRNet通过构建结构因果模型,采用类级和特征级双调整策略消除先验知识干扰。实验在多个轴承/齿轮数据集上验证其有效性,在跨组件任务中准确率最高达93.41%,特征可视化显示更好的类可分性。相比现有方法,CIRNet显著提升了模型泛化能力和可解释性。

hasakie的博客 958

从零构建HFSS连接器仿真模型:以SMP接口的精准复现为例

本文详细介绍了如何从零构建HFSS连接器仿真模型,以SMP接口的精准复现为例。通过获取官方模型、导入技巧、信号路径提取和介质结构复现等步骤,帮助工程师避免常见错误,提升高频电路仿真的准确性。文章特别强调了模型精度对仿真结果的影响,并提供了实用的调试和管理建议。

weixin_29041767的博客 433

【Java】Java中的引用类型(全面解读)

在Java中,引用类型是指一种变量类型,它们用于引用对象而不是存储实际的数据值。当我们创建一个对象时,实际上在堆内存中分配了一块内存空间,并返回了一个指向该内存空间的引用。这个引用就是我们在代码中操作对象的句柄。在Java编程中,理解引用类型是编写高质量代码的关键。通过合理使用不同类型的引用,可以更好地管理内存,避免内存泄漏和内存溢出等问题。同时,对于不同类型引用的特性和用法有深入的了解,能够更好地设计出高效、健壮的程序。

double222222的博客 3289

MATLAB小白也能搞定!BCT脑网络分析工具箱安装与入门指南

本文为零基础用户提供了一份详尽的BCT脑网络分析工具箱安装与入门指南。从MATLAB环境配置、BCT工具箱下载与路径添加,到连接矩阵构建、节点度与聚类系数等基础指标计算,手把手带领神经科学研究者跨越编程门槛,快速掌握脑影像数据分析的核心流程。

threejs5artist的博客 1093

Java中的引用类型

Java中的引用有点像C++中的指针,通过引用可以对堆中的对象进行操作。Java程序中最常见的引用类型是强引用,也是默认的引用类型。当在Java语言中使用 New 操作符创建一个新的对象,并将其赋给一个变量的时候,这个变量就成为指向该对象的一个强引用。 判断一个对象是否存活的标准为是否存在指向这个对象的指针。 Java中提供了四个级别的引用,即强引用(Strong Reference),软引用...

coding 3075

YOLO26 标签分配机制:STAL 小目标感知分配策略

YOLO26提出的STAL标签分配策略通过尺度感知机制优化了小目标检测性能。该方法根据目标面积将检测对象分为小、中、大三类,分别采用差异化的分配参数(TopK数量、IoU阈值和中心度权重),特别是对小目标采用更宽松的匹配条件和更高的中心度权重。实验结果表明,STAL策略显著提升了小目标检测精度(AP_small),同时保持了整体检测性能(mAP),为解决目标检测中尺度不平衡问题提供了有效方案。

一键难忘的博客 795

基于STM32L4XX 、HAL库的ATD5984步进电机驱动器驱动程序应用设计

一、简介: ATD5984是一款内部集成了译码器的微特步进电机 驱动器,能使双极步进电机以全、半、1/4、/1/8、1/16 和1/32步进模式工作。步进模式由逻辑输入管脚MSx选 择。其输出驱动能力达到28V±1.6A。 译码器是ATD5984易于使用的关键,通过STEP管脚 输入一个脉冲就可以使电机完成一次步进,省去了相序 表,高频控制线及复杂的编程接口,使其更适于没有复 杂的微处理器或微处理器负担过重的场合。 在步进操作期间,ATD5984的内部电路可以自动

PP_Cottage的博客 410

Java中的四种引用类型

Java中的四种引用类型

林隐的博客 751

AUTOSAE软件配置-项目标准配置 (PSC) 导入达芬奇( DaVinci Configurator)

文件是“可拆分的”,这意味着如果格式符合 AUTOSAR 拆分规则,则可以与其他。)是一个ARXML文件,主要由OEM提供,其中包含。)工件,可以作为输入文件导入到达芬奇配置器专业版。导入的参数将以只读方式处理。不允许在多个 ARXML 文件中导入一个。的已存在数据或从输入文件派生的数据。可以作为输入文件导入到另一个。文件会覆盖用户配置的基本。元素和诊断数据预配置。定义 [数据结构]。中,可以导出一个或多个。

m0_49148264的博客 1020

JAVA中的引用四种引用类型

关于值类型和引用类型的话题,C++、JAVA、python、go、C#等等高级语言都有相关的概念,只要理解了其底层工作原理,可以说即使是不同的语言,在面试学习工作实践中都可以信手拈来(不要太纠集语言),当然此处我选择了JAVA,虽然我是搞C++的,具体原因都懂就不废话了。 一、值类型与引用类型   1、变量初始化 int num=10; String str="hello"      2、变量赋值   从上图可以显而易见,num是int基本类型变量,值就直接保存在变量中。str是String引.

渣渣 8840

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Java中的四种引用类型是哪些?

从一开始学习Java我们就知道Java的数据类型一般有两种,一种是基本数据类型,另一种是引用数据类型。其中,基本数据类型的值通常储存在栈内存中,用于对该类型的对象进行存储;而引用数据类型则在存储堆中对需要引用的对象进行引用。 引用是Java面向对象的一个特点,如果一个对象不曾被任何变量应用的话,那么整个程序也就无法再使用这一对象。四种引用类型可以说是在学习Java的过程中经常会接触到的。Java中主要包括了四种引用类型,分别是:强引用,软引用,弱引用以及虚引用。 一、强引用 强引用是一种最常见的引用形式,

周二Show 6116

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Java 基础 —— Java 中的值类型与引用类型

一、值类型与引用类型 在 Java 中类型可分为两大类:值类型与引用类型。值类型就是基本数据类型(如 int、double 等),而引用类型是指除了基本的变量类型之外的所有类型(如通过 class 定义的类型)。所有的类型在内存中都会分配一定的存储空间(形参在使用的时候也会分配存储空间,方法调用完成之后,这块存储空间自动消失),基本的变量类型只有一块存储空间(分配在stack中),而引用类型有两块存储空间(一块在 stack 中,一块在 heap 中)。 什么是引用 引用其实就像是一个对象的名字或者别名

IT__learning的博客 4834

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Java中的五种引用类型

在Java中,引用类型的使用决定了对象的生命周期以及GC的回收策略。本文将介绍Java中的五种引用类型,并讨论它们在不同场景下的应用这些引用类型主要用于管理对象的生命周期,帮助垃圾回收器更高效地回收不再使用的对象。接下来我们逐一介绍每种引用类型。

Gaomengsuanjia_的博客 892

java中什么是引用类型_Java中的4种引用类型

原标题:Java中的4种引用类型1、Java中有哪几种引用?它们的含义和区别是什么?从JDK1.2开始,Java中的引用类型分为四种,分别是:①强引用(StrongReference)②软引用(softRefernce)③弱引用(WeakReference)④虚引用(PhantomReference)强引用-StrongReference这种引用是平时开发中最常用的,例如Stringstrong=...

weixin_39541189的博客 258

java中的引用类型

Java中的引用类型 首先java中的引用类型有如下几种:强引用,软引用,弱引用,虚引用。 接下来会结合代码尝试着对这几种引用类型做下讲解。 测试四种引用类型 首先,我们创建了这样一个类: public class Test1 { @Override protected void finalize()throws Throwable{ System.out.println("finalize发生 "); } } 重写了finalize方法 这样在Test1垃圾回收时

小唐同学的博客 293

一文弄懂Java中的四种引用类型

引言 Java虚拟机会为我们管理内存,当内存不足时,通过垃圾回收算法来释放不可达的内存。作为Java程序员我们似乎不需要关注这些。 但是在工作中我们可能会遇到内存充足的情况下,也会出现OutOfMemoryError。 笔者就多次遇到过这种情况,有一次是加载内容过多引起的,通过Xmx2g,在分配了2G内存的情况下出现了内存溢出的问题,最后定位到了是压测的时候压测导出Excel接口没有分页导致一次...

日积月累,天道酬勤 880

《Java中的四种引用类型》

Java实际上提供了四种不同强度的引用类型,它们分别是:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和幻象引用(Phantom Reference)。当一个对象被强引用关联时,它永远不会被垃圾回收器回收,即使内存不足时,JVM宁愿抛出OutOfMemoryError也不会回收强引用对象。当JVM认为内存不足时,会回收只被软引用指向的对象。:最常见的引用类型,只要强引用存在,对象就不会被回收,可能导致内存泄漏如果管理不当。

2301_81117855的博客 447

说一说Java中的四种引用类型?

Java中的四种引用类型各具特点,可根据程序需求选择合适的引用类型。强引用保证对象不被意外回收,软引用和弱引用用于实现缓存或解决内存敏感问题,而虚引用则用于对象回收后的通知和清理操作。合理使用引用类型可以更好地管理内存和避免内存泄漏问题。码农Academy引迈 - JNPF快速开发平台_低代码开发平台_零代码开发平台_流程设计器_表单引擎_工作流引擎_软件架构。

kfashfasf的博客 1055

java中的引用类型概念

java中的引用类型概念     1、什么是引用类型       引用类型(reference type)指向一个对象,不是原始值,指向对象的变量是引用变量。       在java里面除去基本数据类型的其它类型都是引用数据类型,自己定义的class类都是引用类型,可以像基本类型一样使用。     示例如下:     public class MyDate {  

We_soldier的博客 492
上一篇: 继承-java-箴言
下一篇: android--service 你应该记住的一些事-1
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值