Java Memory management and when to destroy object [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have written a small Java program where I create 10 String Objects.
Can someone explain or answer the following questions.
What are the best practices to create a Object. ie; When I create a Object should I also make sure I delete the object once its used. If, How do I delete it?
If I don't delete the object, is that the object will be lying until the program ends?
Is there a way to check the number of active objects when a program is running?
public class Test{
static public void main(String[] args){
for (Integer i = 0; i < 10; i ++){
String s1 = new String("Creating new String");
}
System.out.println("Program COmpleted");
}
}

When I create a Object should I also make sure I delete the object once its used.
No. You can not explicitly delete an Object in Java. For certain memory-intensive use cases, it might make sense to explicitly nullify references to your objects, to help the garbage collector with the cleanup process, but the object itself is not deleted until it is collected by the garbage collector.
If I don't delete the object, is that the object will be lying until the program ends?
No. The garbage collector will take care of deleting it, once there are no references to it anymore. The point in time when this happens is up to the garbage collector - this might also be at the end of your application.
Is there a way to check the number of active objects when a program is running?
Yes, you can use a profiler such as YourKit.
See also
When does Java's garbage collection free a memory allocation?
Garbage Collection in the Java HotSpot Virtual Machine
Java Garbage Collection Basics

What are the best practices to create a Object. ie; When I create a Object should I also make sure I delete the object once its used. If, How do I delete it?
The best practices to create a Object is just when you want to use it.
Also you need to learn about variable scoping.
If I don't delete the object, is that the object will be lying until the program ends?
No, GC will kill un referenced objects
Is there a way to check the number of active objects when a program is running?
You can use any Java profiling tool such as vesualVM

Java is a Garbage Collected language, and therefore, most memory management and cleanup is done for you. This contrary to languages like C++ where one must manually free unused memory and generally be more cautious of possible memory leaks.
To address your specific questions:
Sometimes, it is considered good practice to "null out" unused object references. This is usually only true in specific instances, for example see: Does setting Java objects to null do anything anymore?.
No, not necessarily. If there is nothing pointing to the Object in memory, then the Garbage Collector should free up the unused memory.
You could use a debugger to keep track of the number of objects that are created as you step through your code line by line (I am not sure if this is robust enough a solution for your purposes).

Java has garbage collector. Garbage collector destroys objects when it's no longer used.
you can find gc basics here](http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html)
If you want to profile application use jvisualvm , which is packaged with JDK. If you want to count objects programmatically , use JMX API's (read oracle documentation about JMX)

The JVM automatically recycles objects that are no longer in use (this is called "garbage collection"). This happens when it feels like it, and when running out of previously unallocated memory, and returns the memory used by the unused objects to the unallocated memory pool.
All you have to do is to ensure that there is no variable through which you can use the objects any more - typically by assigning another value - and the rest happens automatically.
The simplest way to see how many objects are used by your program, is to use a profiler. You can use visualvm in the JDK or the one in Netbeans for free.

Related

Is there any way that I can free up memory in the java code that is generated to bind C code via JNI/JNA?

I am using a java library that use JNA to bind to the original C library (That library is called Leptonica). I encountered a situation where free(data) has to be called in the C code to free up the memory. But, is there any function in java that I can free up the memory?
In the C code
void ImageData::SetPixInternal(Pix* pix, GenericVector<char>* image_data) {
l_uint8* data;
size_t size;
pixWriteMem(&data, &size, pix, IFF_PNG);
pixDestroy(&pix);
image_data->init_to_size(size, 0);
memcpy(&(*image_data)[0], data, size);
free(data);
}
The function pixWriteMem() will create and allocate memory to the "data", which you need to do free(data) to free up the memory later.
In Java code, I can only access pixWriteMem(), not the SetPixInternal(), so I have no way to free up the "data", which create a memory leak.
The other comments and answers here all seem to be suggesting that you just rely on the garbage collector or tell the garbage collector to run. That is not the correct answer for memory allocated in C and being used in Java via JNI.
It looks like that execution() does free the memory. The last line you show us is free(data). Still, to answer your the question as you asked it, the answer is "not directly." If you have the ability to add to the C code, you could create another C function which frees the data and then call that using JNI. Perhaps there is more that we are not seeing which relates better to your concern about the memory leak?
Also, be careful about freeing memory allocated by a library you are using. You should make sure that the library doesn't still need it and is leaking it before you go trying to free it.
And now back to memory management in general...
Java is indeed a garbage-collected language. This means that you do not specifically delete objects. Instead, you make sure there are no references to it, then the garbage collector takes care of the memory management. This does not mean that Java is free from memory leaks, as there are ways to accidentally keep a reference hanging around such that the object never gets garbage collected. If you have a situation like this, you might want to read up on the different kinds of references in Java (strong/weak/etc.).
Again, this is not the problem here. This is a C/Java hybrid, and the code in question is in C being called by Java. In C, you allocate the memory you want to use and then you need to free the memory yourself when you are done with it. Even if the C code is being run by Java via the JNI, you are still responsible for your own memory. You cannot just malloc() a bunch of memory and expect the Java garbage collector to know when to clean it up. Hence the OP's question.
If you need to add the functionality yourself to do a free, even without the source code for the C part, you might still be able to write your own C interface for freeing the memory if you have access to the pointer to the memory in question. You could write basically a tiny library that just frees the memory for you, make the JNI interface for it, and pass the pointer to that. If you go this route then, depending on your OS, you might need to guarantee that your tiny free library's native code is running in the same process as the rest of the native code, or if not the same process then at least that the process you run it from has write access to the memory owned by the other code's process; this memory/process issue is probably not an issue in your case, but I'm throwing it out there for completeness.
In Java code, I can only access createData(), not the excution(), so I have no way to free up the "data", which create a memory leak.
Then it sucks to be you.
Seriously, if you want to free memory allocated by a native method and not freed before that method returns, then you need to maintain a handle of some kind on that memory and later pass it to another native method that will free the memory. If you do not presently have such a native method available, then you'll need to create one.
The other question is how to ensure that the needed native method is invoked. Relying on users to invoke it, directly or indirectly, leaves you open to memory leaks should users fail to do so. There are two main ways to solve that problem:
Give your class a finalizer that ensures the memory is freed. This is the core use case for finalizers, but even so, there are good reasons to prefer to avoid writing them. The other alternative is to
Create a reference object (SoftReference, WeakReference, or PhantomReference), associate the reference with a mechanism for freeing the native-allocated memory belonging to the referenced Java object (but not via that object), and register that object with a reference queue. The reference will be enqueued when the object is GC'd, at which point you know to free the native-allocated memory.
That does not necessarily mean that you should prevent users from explicitly freeing the memory, for with enough bookkeeping you can track whether anything still needs to be freed at any given time. Allowing users to release resources explicitly may help keep your overall resource usage lower. But if you want to avoid memory leaks then you need to have a fallback.
No there is no function like C's free() in Java. But you can suggest garbage collector to run by calling System.gc()

How can I delete a specific object? [duplicate]

This question already has answers here:
How to force garbage collection in Java?
(25 answers)
Closed 8 years ago.
How can I manually delete a specific object before the garbage collector would ever collect it ?
For example I want to delete requestToken object. How can I do that ?
The short answer is that you can't, and that you don't need to. The GC will reclaim the memory when it needs to ... and there is no reason to interfere with that.
The only situation I can think of for needing to delete an object sooner is when the object contains information that needs to be erased ... for information security reasons. (The classic example is when you are processing a password provided by the user and you are worried that it might leak via a code dump or something) In that case, you need to implement a method on your object for erasing the object's fields by overwriting them. But this requires careful design; e.g. to make sure that you find and erase all traces of the information.
It is also sometimes necessary to "help" the GC a bit to avoid potential memory leaks. A classic example of this is the ArrayList class, which uses a Java array to represent the list content. The array is often larger than the list's logical size, and the elements of the array could contain pointers to objects that have been removed from the list. The ArrayList class deals with this by assigning null to these elements.
Note that neither of these examples involve actually deleting objects. In both cases, the problem / issue is addressed another way.
It is also worth noting that calling System.gc() is usually a bad idea:
It is not guaranteed to do anything at all.
In most situations, it won't do anything that wouldn't happen anyway.
In most situations, it is inefficient. The JVM is in a better position than application code to know the ergonomically most efficient time to run the GC. (Read this for a first-principles explanation of the ergonomics.)
The only cases where running the GC in production code is advisable are when you are trying to manage GC pauses, and you know that a pause is acceptable at a particular point in time. (For example, when you are changing levels in an interactive game ... )
You cannot delete an object, you can just try to make it eligible for garbage collection in its next cycle. The best you could do is , set the object as null and try calling System.gc();
Note: System.gc() call will only request the JVM to run garbage collector but it cannot force it to.

Java: Delete completely object

I am newbie in Java and my English not enough good, I hope everyone will forgive me.
Question 1:
I have an ArrayList(J2SE) or Vector(J2ME), I have a class(example: Bullet), when i fire, i add a instance of that class to the List and after the bullets hit the target, i need to destroy them and remove them from the list. I want to ask: How to delete completely object which i need to remove, I mean: free all memory which that object was take(Same as delete pointer in C++). With normal object, we can use "= null", but in here, this object is inside a List and we can not use like that. I try to use System.gc(), but that is a bad idea, program will slow down and memory increase more than i not use gc(). If i only use List.remove(bullet_index), memory will increase a bit, but it will not decrease.
Question 2:
Have any Other idea to make a gun shot with "Unlimited number of bullet" and safe with memory.
I making a simple 2D shoting game
You simply can't. Java works over the JVM which provides a managed environment for the allocation and deallocation of your memory through a garbage collector.
You can hint the JVM to clean memory by deallocating unused objects but that's not usually the way it is meant to be used. Just remove the Bullet instance from the list, if there are no other references to it then eventually its memory will be released.
If you really want to save memory you should think about reusing the same instances, this can be done if you plan to have at most a precise amount of bullets at the same time on the screen, so instead that removing from the list the expired one you could add them to a another list which then is used to pick up new bullets (by setting their attributes). In this way you can avoid going over a certain threshold.
Java is memory managed, so you can't reliably free memory. You can be sure that memory will not be freed as long as you have pointers to your object. Setting an object to null means that nothing points to it, but doesn't necessarily mean that it will be garbage collected at that point. For an in-depth explanation on memory management in Java, check this out.
Also, avoid using vectors- they're synchronized, and usually not used in newer code.

After Text was deleted from JTextArea, heap is not empty

I have an application with AWT GUI, and I use JTextArea for logging output. If I erase the text with setText(null) or removeAll() or setText("") and then run garbage collector System.gc(), I notice that the whole text still in memory. How can I really delete the text?
I'm not very familiar with profiler, here is what I see in memory dump after setText(null):
Please have a read on: How Garbage Collection works in Java.
As per the docs System.gc():
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects
NB - suggests. This means that the garbage collector is only suggested to do a clean up and not forced also it may entirely ignore your request, thus we cannot know when the garbage will be collected only that it will be in time.
NB - disgarded objects: this refers to all objects that are not static/final or in use/referenced by any other instances/classes/fields/variables etc.
Here is also an interesting question I found on the topic:
Why is it a bad practice to call System.gc?
with the top answer going along the lines of:
The reason everyone always says to avoid System.gc() is that it is a
pretty good indicator of fundamentally broken code. Any code that
depends on it for correctness is certainly broken; any that rely on it
for performance are most likely broken
and further there has even been a bug submitted for the bad phrasing of the documentation:
http://bugs.sun.com/view_bug.do?bug_id=6668279
.
As #DavidK notes System.gc() is not a useful way to examine this. Using the mechanism described here, most profilers can force garbage collection in a way that, subject to some limitations, is a useful debugging tool.
if there are any String objects holding this content in your client program, please set them to null as well.
Also you don't need to explicitly call the System.gc() mothod. JVM does garbage collects the orphaned objects when ever it needs more memory to allocate for other objects.
you only need to worry about if you a see an out of memory / continuous heap memory increase usage etc.

How to free object in android? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java garbage collection
I know that we have to free object in C, C++ after processing finish to get back the memory. However, I don't know how to free object in java and android. Is that enough for just assign null to the object?
In Java it is un-necessary to free objects.
Java has a built in Garbage Collector which runs when ever it needs to and clear out all resources that are no longer in use in order to free memory. A java developer may make a call to the java runtime to run the Garbage Collecter using System.gc(); however this is just a suggestion to the runtime and may not always result in it being run.
In cases where you are using readers and images, be sure to call .recycle() and .close() where applicable.
A simple java object especially (E.g. model objects) can be freed by garbage collector IF other objects has no reference to it.
If I were you, don't trust too much that garbage collector because there are some objects that you must free, one of them is the Bitmap objects
Bitmaps eat more RAM in your android app.
Bitmap b = createLargeBitmap();
Bitmap b2 = b;
If you remove all references to that object and let garbage collector kill it
b = null;
b2 = null;
you might get a memory leak or OutOfMemory error.
So you need to call recycle() to fully freed the bitmap.
b.recycle();
b = null;
b2 = null;
// Sorry for my wrong grammar :)
In most cases, setting a var to null is enough. A better answer to answer your questions is how to leak the memory which details explained in this post .
Memory deallocation is automatically done by Java garbage collector . You can't force garbage collector to free memory through your code.
Calling System.gc() doesnot guarantee garbage collector to RUN and FREE memory , final decision is taken by Java runtime.
Android (which uses Java language) is a garbage-collected environment, meaning the virtual machine will automatically remove objects which no longer have any references.
Hence the question you should be asking is: how do you ensure your program does not use too much memory. This is normally achieved by ensuring you don't put too many objects in your in-memory data structure, persist your information into file system etc.

Categories