I understand that strings (at least in Java) are immutable. I'm not trying to empty the contents of the string.
If I did, I'd use this: output.setText( outputString );
My question is: if you wanted to minimize the amount of space a program requires by relinquishing the bits storing the string, is there a way to do this?
In Java, garbage collection is done by JVM. So the answer to your question is no.
At best you can make the object eligible for garbage collection by making sure that the Object is not referenced anywhere.One way is to make any variable reference as null which is referring the object in question and calling System.gc().
String outputString ="Some Value";
outputString =null
The object "Some Value" in heap memory is not being referenced from anywhere and becomes eligible for garbage collection.
System.gc() hints the JVM to do garbage collection. There is no guarantee that the object will be freed from heap memory.
There is an automated garbage collector in Java.
In Java, as the developer does not explicitly remove the memory in the
program code, the garbage collector finds the unnecessary (garbage)
objects and removes them.
http://www.cubrid.org/blog/dev-platform/understanding-java-garbage-collection/
Related
I am trying to understand what happens to a string when null is assigned to it.
So, I have a String str = new String("abc"); It uses some space in memory.
When str is assigned null, i.e str = null, what happens to the memory that was used to create "abc" . Does it still use space in memory?
Java is garbage collected. The memory allocated for the string will be freed at a feature point in time determined by the garbage collector. See Java Garbage Collection Basics for details.
Update: as commenters pointed out string interning might prevent the string from getting garbage collected. Details depend on many things like the scope of the reference, JVM and Java version.
As every java developers know java Objects will be garbage collected when no longer in use.
I want to know how JVM identify which object have to pick for garbage collection.
(say eg..If I have 10 objects. out of 10 if 2 objects are garbage collected how jvm finds that two object).
JVM uses "mark and sweep" algorithm(If im right).
1)For example i providing string object scenarios below
class Sample{
public static void main(Strings args[]){
String s1=new String("10");
String s2=new String("20");
String s3=new String("30");
String s4=new String("40");
String s5=new String("50");
String s6=new String("60");
String s7=new String("70");
s1=null; //now s1 is eligible for gc collection
s2=null; //now s2 is eligible for collection
}
}
//now s1 & s2 are eligible for gc collection.If i expicitly made to null references(s1,s2) become null but what happens to the memory allocated on heap? will it be freedup?
Actually nothing happens. The memory used by s1 and s2 will be reused only when GC starts working and this will only happen when JVM decides and it may never happen. In your case GC will hardly ever start.
It's covered fairly succinctly here: http://www.brpreiss.com/books/opus5/html/page424.html
The mark-and-sweep algorithm is called a tracing garbage collector
because is traces out the entire collection of objects that are
directly or indirectly accessible by the program.
The objects that a program can access directly are those objects which
are referenced by local variables on the processor stack as well as by
any static variables that refer to objects. In the context of garbage
collection, these variables are called the roots . An object is
indirectly accessible if it is referenced by a field in some other
(directly or indirectly) accessible object.
So when you do s1=null; you are disconnecting the root, and the corresponding instance becomes eligible for collection.
The actual "collection" (freeing of the heap) occurs when the GC actually executes. As to exactly when this occurs there is not a one-size-fits-all answer to that. See What the frequency of the Garbage Collection in Java?
Assigning null to any reference doesn't free up the memory. It only makes the reference available to remove using garbage collector. Means now this reference allocated memory can be free when garbage collector will run.
If any live thread can't access the object by any means then that object becomes eligible for garbage collection. But there is no guarantee of GC to run as it depends upon JVM internal logic and algorithm.
Generally it happens when JVM thinks that its time to clear up some memory usage.
In your case s1 and s2 are eligible to be GCed but we can't say when it will happen.
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static references
SEE HERE
Java objects are eligible for garbage collection when the reference count of that object is 0. Reference count being 0 indicates that "that particular object is not referenced by any variable, hence it can not be used anymore". Garbage collector in the first pass mark all such objects whose reference count is 0 and in the second pass it sweeps all the marked object. Hence it is mark and sweep algorithm.
will it be freedup?
It depends on the garbage collector, when the garbage collector re-run after you made the s1 and s2 null, then they will be eligible for garbage collected. But, making reference null won't immediately release the object from the memory
Here is the code snippet.
method(){
String s1="abc";
String s2 = new String ("abc");
s1=null;
s2=null;
--------
---------
}
At the end is s1 & s2 objects are exists? How you will make sure these objects are garbage collected ?
Objects referenced to by s1 and s2 are eligible for garbage collection once s1=null and s2=null provided that no other references to that Object exists or when the method exits, provided that the Objects were only referenced by the local variables.An object once created uses some memory and the memory remains allocated till there are references for the use of the object.When there are no references for an object, it is assumed to be no longer needed and the memory occupied by the object *can be reclaimed.*An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null.
There are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen. Java programmers can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection. Forced GC is sign of bad coding.Once should in turn always look to minimize creation of unnecessary objects and references to those objects.
They get garbage Collected after they go out of scope.
Unless you're actually having serious performance issues, I'd stop worrying about it so much and let the garbage collector do it's thing.
You should be careful though, there are some kinds of elements such as file streams, open sockets, and such that are not managed like that. you have to close those.
If the question is how to make sure, the answer is fairly simple. You can never make sure that any object will be garbage collected. Read this to understand what garbage collection really is and how to reason about it.
If the question is how to hint for a collection, then set all the references of unwanted objects to null and call System.gc(), which will request (not force) a collection. Nothing is guaranteed to be released using this method, but often it's the closest thing you can get.
If you want to do this specifically for strings, because they may contain sensitive data or something along these lines, use a char[] to store that data instead of a String, because you can change the primitive values of the array at will and erase them when you're done.
Garbage collector runs periodically(time period is JVM dependent). Java maintains table of objects and its references when reference is broken (probably by assigning null to reference) then on next execution of GC (garbage collector) object's having no reference will be deleted (If something goes wrong with GC then object will not garbage collected - very very rare condition), which is totally dependent on JVM. You can send request to JVM to run GC by using following code (Processing your request is once again JVM dependent):
Runtime.getRuntime().gc();
or
System.gc();
Programmer don't have to worry about the running GC mostly JVM will handle execution of GC. There are lots of enhancements made to the garbage collectors. Java (latest version) comes with G1(Garbage First) collector which is a server-style garbage collector which runs more effectively. G1 is a great replacement for CMS (Concurrent Mark-Sweep Collector).
If you want to know more about garbage collector then you should read the pages:
[http://docs.oracle.com/javase/7/docs/technotes/guides/vm/gc-ergonomics.html][1]
[http://docs.oracle.com/javase/7/docs/technotes/guides/vm/cms-6.html][2]
[http://docs.oracle.com/javase/7/docs/technotes/guides/vm/par-compaction-6.html][3]
String s2 = new String ("abc");
Here 'abc' will be created in regular, garbage collectible heap area.
So as soon as you make S2 null, this string object is eligible for garbage collection.
This is assuming that your programm do not have any other reference to this particular string object "abc".
String s1="abc";
In this case, "abc" will be created in special area of heap called literal pool or string pool. Making "abc" null does not make "abc" eligible for garbage collection since JVM will try to reuse this "abc" in future.
Baseline in this case is, normal garbage collection rules won't apply here.
Hope this helped. :-)
What happens if you run the following code..
while (true) {
String x = new String("ABC");
}
in terms of memory?
Is String x allocated on the stack or on the heap? Will the program eventually crash because of a memory overflow, or will garbage collection prevent that? Does the new keyword always create the object on the heap? When is an object created on the stack?
Thanks!
Is String x allocated on the stack or on the heap?
x isn't a String. It is a reference to a String. The reference is a local variable, and so goes on the stack. The String is an object, and so goes on the heap.
Will the program eventually crash because of a memory overflow
Probably not.
or will garbage collection prevent that?
It should.
Does the new keyword always create the object on the heap?
Yes.
When is an object created on the stack?
Never ... unless the JVM decides it cannot escape the current scope and so decides to do so.
Using new, yes, puts objects on the heap. Objects that are no longer accessible by any thread can be garbage collected. Whether you run out of memory or not depends on the size of data your program uses, and if you are good at 'releasing' objects you dont need any more (think: memory leaks are bad).
In your example, you will be running the garbage collector like crazy, which I think is what you are intending to demonstrate.
Local variables go on the stack.
In theory, new creates on the Heap, and non-objects (i.e., ints, chars and so on) are created on the stack. The only exception, afaik, are strings, created on the stack as well. In practice, the JIT compiler of many modern JVMs will see that, in some cases, objects created with new can be created on the stack (for example, local objects that are not referenced outside of the current function).
The garbage collector will take care of the deallocation for you, that's its purpose, but of course you can run out of memory if you create and keep references on too many objects at the same time (try creating a list with a billion strings, for example).
private void func()
{
String str = "hi!";
}
this is my code.
suppose I called func() in the onCreate event.
I want to the near exact time, if thats possible to be determined, when GC will free the memory used by str.
Actually str stores a password.
and i want to free it as soon as I can.
currently after using str I set its value to something irrelevant.
I heard GC is the only thing that can free memories?
is that correct?
is there any other way of freeing the memory of a variable.
I want to the near exact time, if thats possible to be determined,
when GC will free the memory used by str.
Bad luck, you can't have it.
Solution: store it in a char[] instead of a String, and zero out all elements of the char[] when you are done with it.
Once the garbage collector is satisfied that there is no longer references to it, it becomes eligible for garbage collection.
However, because this is a String, i recall this literal will still be in the String pool, however its object reference will be destroyed by the GC.
You can't however influence the behavior of the GC.
In your case of the method, the variable goes out of scope each time the method exits, when it goes out of scope, it becomes eligible for GC, but whether GC decides to free it, we can't control or predict.
First, java will hold this string as long as it wants. Theoretically until the JVM terminates. So what? Who can connect to it and bring the value? And how?
But if you afraid very much you can call System.gc() that will probably trigger the GC to run and remove the value. Still no guarantee.
There is yet another trick. String contains its content is private field char[] value. You can overwrite it using reflection, so no one will know your password.
The str is not the problem in your case, when you are declaring a string, it is allocated in string pool of your application. You should create an array of chars instead.
Regarding the GC, you don not have any assurance when will collect that memory.
I don't know very well the Dalvik VM but in standard Java there is no way to freeup the memory from your example because the string "hi!" lives in the constant pool.
If you change to
String str = new String("hi!");
that gives a string on the heap and can be GC.
You can call System.gc() but this is merely advisory if you look at the java docs. You can't force a garbage collection in java and in general it's not a good idea to try.
If you really need a solution for this, you'd need to write your own custom password reader/writer using either byte arrays or JNI, and of course be very careful the password never gets turned into an Object. Otherwise you've lost.