0

my question is somewhat simple. All I want to know is, can you remove and instance of an object from the RAM in java? Like, when you type:

new Cat();

You don't assign a variable to that new cat, so you can't access it. This happens in games. It says something like, "new Pig();", and it creates an instance of the pig. But what happens when the pig dies? How is it deleted? Can it call its own method to erase itself?

Thanks.

4 Answers 4

5

The garbage collector cleans it up at some point after nothing "live" can get at it.

You can't explicitly delete it. It will just be garbage collected at some point.

There are any number of articles about this - just search for "java garbage collector" for far more details. Ideally, read recent articles as the state of the art moves pretty quickly when it comes to garbage collection.

Sign up to request clarification or add additional context in comments.

Comments

2

Here is a good article on how the garbage collector works in Java

http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html

Comments

1

You can't, the garbage collector is in charge of removing instances from memory.

You can invoke the garbage collector using System.gc() but that method doesn't guarantee the cleanse from memory.

Comments

0

It is not possible to do that manually. Garbage Collector in JVM takes care of it. Java is not like C or C++ where you have free() and delete() respectively for this purpose.

The closest thing you have is System.gc(); and Runtime.gc(); but they do not force garbage collector. They just suggest.

Garbage Collection itself can be forced: Force Garbage Collection. Using the Java Virtual Machine Tool Interface, the function

jvmtiError ForceGarbageCollection(jvmtiEnv* env)

will "Force the VM to perform a garbage collection."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.