我可以用 sun.misc.Unsafe 覆盖对象吗?
如果一个对象是同一类的实例,它们的大小相同,我可以使用 sun.misc.Unsafe 重写一个对象吗?
编辑: 我所说的“覆盖”是指“删除”第一个对象,然后用第二个对象填充内存。是否可以?
Can I override one obejct with another if they are instance of same class, their size is the same, using sun.misc.Unsafe?
edit:
By "override" I mean to "delete" first object, ant to fill the memory with the second one. Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是和不是。
是 - 如果您使用 Unsafe 分配一些内存并写入 long,然后在里面再写一个long(例如),那么是的,你已经删除了第一个对象并用第二个对象填充了内存。这与您可以使用 ByteBuffer。当然,long 是一种原始类型,所以它可能不是你所说的“对象”。
Java 允许这样做,因为它可以控制分配的内存。
否 - Java 使用对象引用,并且仅提供对这些对象的引用。此外,它倾向于在内存中移动对象(即,用于垃圾收集)。
如果您正在尝试这样做,则无法获取“物理地址”并将内存内容从一个对象地址移动到另一个对象地址。此外,您实际上无法“删除”该对象,因为它可能是从代码中的其他地方引用的。
但是,总是有可能通过
A = objectB;
将引用 A 指向另一个 objectB 而不是 objectA;您甚至可以使用Unsafe.compareAndSwapObject(...)
使此原子化代码>.解决方法 - 现在,我们假设引用 A1、A2、A3 指向同一个 objectA。如果你想让它们突然都指向objectB,你不能使用
Unsafe.compareAndSwapObject(...)
,因为只有A1会指向objectB,而A2和A3仍然会指向objectA 。它不会是原子的。有一个解决方法:
您可以定义一个公共静态引用并让您的代码在任何地方使用
AtomicReferenceChange.myReference
,而不是对同一对象进行多个引用。如果要自动更改引用的对象,请使用静态方法changeObject(...)
。Yes and no.
Yes - If you allocate some memory with Unsafe and write a long, then write another long in it (for example), then yes, you have deleted the first object and filled the memory with a second object. This is similar to what you can do with ByteBuffer. Of course, long is a primitive type, so it is probably not what you mean by 'object'.
Java allows this, because it has the control on allocated memory.
No - Java works with references to objects and only provides references to these objects. Moreover, it tends to move objects around in memory (i.e., for garbage collection).
There is no way to get the 'physical address' and move memory content from one object address to another, if that's what you are trying. Moreover, you can't actually 'delete' the object, because it may be referenced from elsewhere in the code.
However, there is always the possibility of having reference A point to another objectB instead of objectA with
A = objectB;
You can even make this atomic withUnsafe.compareAndSwapObject(...)
.Workaround - Now, let's imagine that reference A1, A2, A3 point to the same objectA. If you want all of them to suddently point to objectB, you can't use
Unsafe.compareAndSwapObject(...)
, because only A1 would point to objectB, while A2 and A3 would still point to objectA. It would not be atomic.There is a workaround:
Instead of having multiple references to the same object, you could define a public static reference and have your code use
AtomicReferenceChange.myReference
everywhere. If you want to change the referenced object atomically, use the static methodchangeObject(...)
.