"__________ for Java" as "free in C" or "delete in C++"
What keyword 开发者_如何学编程or function is used in Java to release memory?
You don't release memory in Java. it is garbage collected by the JVM.
Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program.
Java is garbage collected, which means that you don't explicitly release memory. Instead, the JVM automatically frees memory when it is no longer referenced. You explicitly de-reference something by setting any variables you had that were referencing it to null
, but that doesn't necessarily guarantee it'll be garbage-collected immediately.
It is garbage collected by JVM. So we don't need to explicitly release the memory.
In java, the JVM, memory is automatically reclaimed when objects are garbage collected. Objects in java become eligible for garbage collection when they are no longer referenced (or not strongly referenced (weakly referenced)). That does not mean there will be no memory leaks in java programs. If you are not careful there can still be memory leaks, as given in classic example:
public class Stack {
private Object[] elements;
private int size = 0;
public Stack(int initialCapacity) {
this.elements = new Object[initialCapacity];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
/**
* This method leaks memory
*/
public Object leakyPop() {
if (size == 0)
throw new EmptyStackException();
// here is the leak, This object will never be GC'd because its still
// referenced in the elements array
return elements[--size];
}
/**
* This has a fix to avoid memory leak
*/
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
// To avoid the leak you need to eliminate the reference here explicitely
elements[size] = null;
return result;
}
/**
* Ensure space for at least one more element,
*/
private void ensureCapacity() {
//...
}
}
Perhaps you want System.gc()
?
精彩评论