我正在寻找类似于 java.lang.ref.WeakReference 的弱引用实现,但它提供了 set() 方法或其他重新引用创建的方法弱引用对象。这是一个例子:
MutableWeakReference ref = new MutableWeakReference(someObject);
ref.set(anotherObject);
我需要这个来避免对象创建,在我的例子中,这会使执行时间减慢一个数量级,因为我不断地更改弱引用引用的对象。
我尝试从 JDK 复制代码,但这似乎不可能,因为 java.lang.ref.Reference
使用内部的 sun.misc.Cleaner
类。我还查看了 Android 实现,但似乎它依赖于 Dalvik VM 进行垃圾收集。我想知道这是否真的可以在不改变 JVM/环境的情况下实现。
I am looking for a weak reference implementation similar to java.lang.ref.WeakReference
, but which offers a set()
method or some other way of re-reference the created weak reference object. Here is the example:
MutableWeakReference ref = new MutableWeakReference(someObject);
ref.set(anotherObject);
I need this to avoid object creation which, in my case slows down the execution time by an order of magnitude, because I am constantly changing the object to which my weak reference refers.
I tried to copy the code from JDK, but it seems impossible since java.lang.ref.Reference
uses the sun.misc.Cleaner
class which is internal. I also looked on Android implementation but it seems it depends on Dalvik VM for Garbage collection. I wonder if this is actually possible to implement without changing the JVM / environment.
发布评论
评论(3)
我很困惑为什么您需要在迭代器中使用
WeakReference
。WeakReference
的正常用例是对对象的长期引用。但迭代器通常是短期对象,迭代通常是短期过程。事实上,它/它们在短期内使用对目标对象的普通(强)引用不应该是一个问题。同样,这表明您根本不应该使用
WeakReference
。是否有特殊原因导致常规参考资料对您不起作用?
I'm puzzled why you would need to use a
WeakReference
at all in an iterator. The normal use-case forWeakReference
is for long term references to objects. But an iterator is typically a short term object, and an iteration is typically a short term process. The fact that it / they use an ordinary (strong) reference to the target object in the short term shouldn't be a concern.Again, this suggests that you shouldn't be using a
WeakReference
at all.Is there a particular reason why won't a regular reference work for you?
难道不是可以将您的引用封装在一个简单的文件中
并创建
WeakReference>
吗?不,您可能无法“重新实现”
WeakReference
。它是 JVM 支持的类。您确定是
WeakReference
实例的创建导致速度减慢吗?我不认为做一些事情
会更昂贵。
Wouldn't it just be possible to encapsulate your references in a simple
and create
WeakReference<MyOwnReference<WhatEver>>
?No, you probably can't "reimplement" the
WeakReference
. It is a JVM-supported class.Are you sure it is the creation of
WeakReference
instances that slows it down? I wouldn't think doinginstead of some
would be that much more expensive.
您无法自己编写弱引用。它是 JVM 专门处理的“特殊”类。
只需使用新的弱引用
You can't program a weak reference yourself. It's a "special" class that JVM handles specially.
Just use a new weak reference