views:

105

answers:

2

I'm writing an array-backed hashtable in Java, where the type of key and value are Object; no other guarantee.

The easiest way for me code-wise is to create an object to hold them:

public class Pair { 
    public Object key;
    public Object value;
}

And then create an array

public Pair[] storage = new Pair[8];

But how does the jvm treat that in memory? Which is to say, will the array actually:

  • be an array of pointers to Pair() objects sitting elsewhere, or
  • contain the actual data?

edit

Since the objects are instantiated later as new Pair(), they're randomly placed in the heap. Is there any good way to ensure they're sequential in the heap? Would I need to do some trickery with sun.misc.unsafe to make that work?

Explaining my motivation, if I want to try and ensure that sequential items are in the same page of memory, is there any way to do this in Java?

+5  A: 

The array will be an object on the heap containing pointers to the Pair objects which will also be on the heap (but separate from the array itself).

Paolo
+1. Any good way to group them together? Otherwise, it seems like non-primitive arrays would be a sloppy mess in memory.
Dean J
The array itself will be a contiguous block and if the other objects are allocated at the same time (assuming no other threads and no GC runs in the middle) then they'll be placed in next to each other in memory too. However, there's no guarantee they'll be in the same memory page. You could serialise the objects into a byte array yourself and force the layout that way, but it won't be pretty.
Paolo
Not so much worried about pretty at this point; getting around the hardware abstractions never looks good. Thank you!
Dean J
+1  A: 

No, the storage array will only contain pointers to the actual Pair objects existing somewhere else on the heap. Yet, remember to instantiate 8 Pair objects and make each element of the array point to these objects. You need to have something like this after the code that you have written:

for(int i=0;i<storage.length;i++)
    storage[i] = new Pair() ;

Only then will the Pair objects be created and correctly referred to by the storage array.

euphoria83
Oh, I know I have to initialize the objects, but I was wondering if the array guaranteed the objects would be sequential in memory; that sounds like a definite no. +1, thanks for the answer!
Dean J
i am not sure if chronologically-sequentially created objects are contiguous in memory, but it seems unlikely considering the garbage collection is done automatically in the language. But, since the objects are not contained in the array, there is no guarantee about this. The pointers in the array must of course be sequential.
euphoria83