开发者

Java Heap Indirect Access

Currently I use a HashMap<Class, Set<Entry>>, which may contain several millions of short-lived and long-lived objects. (Entry is a wrapper class around an Object and an integer, which is a duplicate count).

I figured: these Objects are all stored in the JVM's Heap. Then my question popped in my mind; instead of allocating huge amounts of memory for the HashMap, can it be done better (less memory consumption)?

Is there a way to access Objects in the Java Heap indirectly, based on the Cl开发者_如何学编程ass of the Objects?

With "indirectly" I mean: without having a pointer to the Object. With "access" I mean: to retrieve a pointer to the Object in the heap.


I don't really understand the purpose of your code, but I fear your code involves some frequent OutOfMemoryError, no ?

Anyway.

You can get references to obejcts that won't prevent these objects from being garbage-collected, like SoftReference (the default one used when you do myObj = thisObj;), WeakReference, and PhantomReference.

So, you could (and should, inf act, use WeakReference to let the GC do its work). However, for dynamic memory exploration, there are applications already existing, like VisualVM, that uses a protocol allowing an external process to query the VM : JVMPI.

i think you really should take a look at this.


No. Basically, each object knows its class, but a class does not know all its objects - it's not necessary for the way the JRE works and would only be useless overhead.

Why do you need to know all instances of those classes anyway? Maybe there's a better way to solve your actual problem.


HashMap overhead shouldn't be that much. And I don't think it's possible to rummage around in the heap with the public Java API. The Objects probably won't be there anyway, as they will be collected if there is no reference.

What you could do, if HashMap overhead is to much, is allocate an array, like Object[] or Entry[]. You'll loose the quick-access, add and delete possibilities of course (given that an array is fixed size it's hard to add items if the array is too small).

When using the array solution you'll have to know beforehand how many entries you will have, or copy the array in a larger array when needed, take null values into account if you allow deletes and so forth. What an ArrayList does, basically.


The map contains only pointers to the objects on the heap. I do not think you can do better then that,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜