If the object is referenced as then it is automatically frees the memory in j2me or not frees the memory in j2me?
Im a j2me developer. Now im developing a mobile application using j2me. I had a doubt,
In java, If a crea开发者_如何学JAVAte an object , then after some time we does not want it means,we make it null ,then it is automatically frees the memory and goes to garbage collection.
String str1=new String("Thamilan"); //Allocating a memory for str1
.......
......
str1=null; //Frees the memory of str1
The above code str1=null
frees memory, My doubt is like that if we refer any object to null then it is goes to garbage collection (memory frees) in j2me is correct or not.
Please help me. The answer is very helpful to me. Because i had a problem of memory constraints in my mobile application.
Thanks & Regards
Yes, if all references to an object go away, it becomes eligible for garbage collection and the memory for it will eventually be freed. This will in general not happen immediately, but sometime later in a background thread or when the program threatens to run out of memory. This is true for J2ME as well.
What you should take care of in J2ME (even more so than in general) is to preserve memory at the allocating end, i.e. not create huge amounts of objects in the first place if it can be avoided.
PS:
String str1 = new String("Thamilan")
is better written as (and uses more memory than)
String str1 = "Thamilan";
String str1=new String("Thamilan"); //Allocating a memory for str1
.......
......
str1=null; //Frees the memory of str1
If all references go away, then memory will eventually be freed. But beware that writing this kind of code in stack (i.e. local variables, inside methods) offers no advantage at all; the compiler can infer if the variable can't be referenced after some point, so explicitly setting it to null
has no effect whatsoever; the assignment will probably be optimized away immediately.
For heap (i.e. instance variables, inside classes) this kind of null
ing may be useful, though. The compiler or the JVM has no way to know if someone is going to reference that variable in the future, possibly via reflection, so it must keep the object around unless its reference is null
'd.
Better calling System.gc();
to call the garbage collection.
精彩评论