Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete unused variable's memory in java

I know that Java have its own garbage collection, but sometimes I want to delete the garbage manually. Is there any way to do the work like that? And considering that I have a long or very long function which declares many variables, is this a good idea to delete the unused memory immediately after using instead of auto collection at the end of the function? If I delete garbage manually, does it affect the speed of my application? Thanks for helping!

like image 817
Kingfisher Phuoc Avatar asked Jul 04 '12 14:07

Kingfisher Phuoc


People also ask

How do you remove unused objects from memory in Java?

There is no direct and immediate way to free memory in java. You might try to persuade the garbage collector to take away some object using the well known: Object obj = new Object(); // use obj obj = null; System. gc();

What is unused memory in Java?

In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.

How do you destroy a variable in Java?

Set clear() method in Java with Examples Set. clear() method is used to remove all the elements from a Set. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing Set.

How does garbage collector remove unused references?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.


1 Answers

There is no direct and immediate way to free memory in java. You might try to persuade the garbage collector to take away some object using the well known:

Object obj = new Object(); // use obj obj = null; System.gc(); 

but there is no guarantee that this will actually free memory immediately.

While this applies to heap memory, stack allocated items can only be freed when the function returns.

like image 146
Tudor Avatar answered Oct 04 '22 13:10

Tudor