Question

There are several computer programming languages using JVM bytecode as, lets say, target language for their interpreter/compilers. It seems to me that many new programming languages (less than 15 years old) run over JVM and I wonder whether explicit memory deallocation is forbidden for all of them:

Is it possible to explicitly allocate-deallocate memory using in bytecode through any instruction? Is, on de contrary, the garbage collector always resposible for memory liberation?

Was it helpful?

Solution

The JVM abstracts away all memory management. There is no bytecode for memory deallocation, just as there is no bytecode for memory allocation or direct memory access. If you want to do that, you have to use native code, directly or indirectly.

OTHER TIPS

One of the absolute tenets of the JVM is that objects are absolutely positively guaranteed to last at least as long as any references to them. If the objects in a group hold strong references to each other, but the only references to them outside the group are encapsulated in WeakReference objects, then all objects in the group, and all references to them, will cease to exist, simultaneously (the WeakReference objects may continue to exist, but they won't hold references to anything anymore).

A consequence of this is that the memory for an object cannot be reused unless or until the JVM can be certain that no references to it exist. Because it would take just about as long to ensure that no references existed to one particular object as it would take to perform a garbage-collection on all objects that were about the same age or newer, there's really no benefit to trying to recycle memory sooner. This is especially true if one considers that the GC runs when memory is needed. Until memory is needed, there's no advantage freeing it up.

I come back to this question, after two years, when I just found that the project Tungsten within Apache Spark is using a kind of hack to allocate and de-allocate memory in the heap using the JVM.

It's not new, so it was possible to do. You can find more details here whence I got the following example:

public DirectIntArray(long size) {
  startIndex = unsafe.allocateMemory(size * INT_SIZE_IN_BYTES);
  unsafe.setMemory(startIndex, size * INT_SIZE_IN_BYTES, (byte) 0);
  }
}

public void setValue(long index, int value) {
  unsafe.putInt(index(index), value);
}

public int getValue(long index) {
  return unsafe.getInt(index(index));
}

private long index(long offset) {
  return startIndex + offset * INT_SIZE_IN_BYTES;
}

public void destroy() {
  unsafe.freeMemory(startIndex);
}

The GC is completely unaware of the memory this way allocated. I call it a hack because it uses code reflection to open internal methods which should only be used by the ClassLoader to allocate memory for instances creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top