-1

As it can be seen in the following minimal code, I want when the JAVA object finished, the allocated object in test variable be unallocated. What can I do to unallocate this object? I used null and system.gc, but they don't work to unallocate the object.

package chatclient;
/**
 *
 * @author root
 */
import java.io.IOException;


public class ChatClient {
    private void run() throws IOException {
        long test[]=new long[10000000];
        test[10000]=100;
        // Process all messages from server, according to the protocol.
        test=null;
        System.gc();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize(); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * Runs the client as an application with a closeable frame.
     */
    public static void main(String[] args) throws Exception {
        while(true){
            ChatClient client = new ChatClient();
            client.run();
        }
    }
}
  • 1
    You can't, explicitly. – Andy Turner Feb 22 '17 at 11:47
  • 2
    To clarify the above comment a little: [read this question](http://stackoverflow.com/questions/66540/when-does-system-gc-do-anything). Basically, the `System.gc()` call is just a hint to the JVM that perhaps, maybe, if it feels like it, it should possibly run a garbage collection. No pressure, though. – Phylogenesis Feb 22 '17 at 11:50
  • Please **edit** the question to say what you mean by "do not work". What are you looking at that makes you believe the object is not "freed"? And since "free" is a C concept, what do you mean by it here? – slim Feb 22 '17 at 11:53

1 Answers1

2

Java is a Garbage Collected language. It does not provide a means to explicitly free memory. Instead, if an object can't be reached, it is a candidate for Garbage Collection, and will be removed when the runtime's GC algorithm decides it needs the space.

The GC algorithm in modern versions of Java is incredibly sophisticated, and high performing. However it's quite normal for it to not remove objects from the heap, when memory usage is not approaching configured limits.

This is a great boon to the programmer - most of the time you simply don't need to worry about memory management. However if you're running in a very tight memory environment, Java might not be the right tool for you.

slim
  • 40,215
  • 13
  • 94
  • 127