Java object Garbage collection by JVM - java

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

Related

How to not reference an Object when it is not used so it gets deleted by GarbageCollection

I have an array list that will constantly have different amounts of items in it.
It won't be deleted when it's empty.
Can this cause memory leaks?
I see people saying to make something eligible for garbage collection you have to de-reference it. What does this mean?
An empty array is not a memory leak risk.
Memory leaks happen when a collection accepts unlimited references. It's hard to see how an empty list will be a problem.
An object that has a reference to an empty list will keep it in memory.
The garbage collector will mark an object as eligible for garbage collection when no other object refers to it. All references to that object have to be removed.
You can set reference to null to "de-reference" object. Like this for example:
Object o = new Object();
o = null;
In java when nothing points to the object (there is no reference to the object) then the object is "eligible" for garbage collector.
When it comes to memory leaks it really depends on your situation but it is possible to have some leaks due to not de-referencing.
Developers sometimes talk about "memory leaks" in Java. What they mean is that they have a lot of memory allocated that they no longer require, but in principle the application could reference if it wanted to. This is different from the "classical memory leak" which you would see in a language like 'C' where the application explicitly has to allocate an deallocate memory. As this question is about Java I won't concern myself with the "Classical Memory Leak", but just understand that the two are different
As #hdw3 correctly states, in Java an object is eligible for garbage collection if you have no reference to it. This is a specific case of a more general rule - an object is eligible for garbage collection if it can not be referenced in any way by your application. There is a subtle but important difference here...
Case 1
If you have a reference to object 'A' and that object has a reference to object 'B'. (This could be your ArrayList if contains a single item.) Neither object is eligible for garbage collection as the String can be referenced through the list.
As soon as you loose the referenced to your first object then neither object is accessible from your application, so both become eligible for garbage collection.
Case 2
Imagine you have a reference to object 'A' and that object has a reference to object 'B', AND object 'B' has a reference back to object 'A'. Objects 'A' and 'B' are both accessible so neither are not eligible for garbage collection.
As soon as you loose your reference to object 'A' then 'B' also becomes inaccessible. Both objects become eligible for garbage collection, even though they reference each other.
You can loose your reference to the object in a couple of different of ways.
The usual way is to simply exit a method that has the only reference to the object.
As #hdw3 points out reassign your reference so that it points to something
Something called "SoftReferences" exist, but you only need to worry about them if you are implementing large caches.
What you'll find is that in Java the Garbage Collector almost always does the right thing for you and you don't need to bother about memory too much.
The Java "Memory Leak" I mentioned earlier occurs if you've got a large structure you application no longer requires, but in theory the application could reference objects in that structure. For example you've got a massive List of Strings, you've finished processing them but haven't existed the method yet. This is when you'd assign your reference to null, to make ALL objects in the structure eligible for garbage collection

Java Anonymous object and Garbage collection part -1

public void function(){
new Student().setName("john");
}
public void function(){
Student student = new Student();
student.setName("john");
}
Does GC behave differently for both of the snip?
I mean which case (CASE-1/CASE-2) is more GC efficient in terms of
Time?
Does GC behave differently for both of the snip?
No. Once the setName method has been invoked, the Student object created with new Student is no longer reachable and can be garbage collected.
I mean which case (CASE-1/CASE-2) is more GC efficient in terms of Time?
Neither is more efficient. The first case will have one less assignment in the bytecode. This does not affect GC whatsoever.
From the JLS
A reachable object is any object that can be accessed in any potential
continuing computation from any live thread.
In both snippets, after the invocation of setName, the Student object is no longer reachable (assuming the constructor and the setName method don't leak references to the object - but even in that case, the behavior of both snippets would be the same).
In the first case you don't assign the newly created object to a variable, hence it becomes unreachable for the code (and thus becomes a candidate for garbage collection) as soon as setName (String name) method returns.
In the second case local variable student will prevent the student object from being garbage collected until it goes out of scope. In other words, in the second snippet the student object will continue to be a live object after setName(String name) returns and will become a candidate for garbage collection only after the method function() returns.
UPDATE:
In terms of the time required for garbage collection both cases are equal since in all of them you end up having one garbage object.
Answer for question is no.
Gc behaves nearly same for both cases.
Garbage Collector has a unpredictable behavior. But
Any Object which is no longer referred or is no longer in use is eligible for garbage collection.
Case 1 : Main objective of anonymous object is for instant use (one time use). So after line "new Student().setName("john");" , your anonymous object is not in use so it will be GC.
case 2 : Student student = new Student();
student.setName("john");
After this line student reference is no longer referred so it will be GC.
There are few chances that in case 2 student reference may be leaked but GC is smart enough to handle this.
Now in case 1 if you want object for one time use then go for anonymous object as Objects are created in heap memory and GC sweep heap memory. Stack memory are managed in such way that memory used by stack is reclaimed automatically.
You can referred this link for more.

Garbage Collection and InComplete Constructed Object

This may be a very naive Question?
Suppose i have Class Something like this
class SlowConstructor {
private final int a;
private final String unReachableString;
public SlowConstructor(String random) {
unReachableString = "I am not reachable will GC will collect me " + random;
Thread.sleep(1000*3600); // ignoring Exception check for readbility
a = 100;
Thread.sleep(1000*3600);
}
}
So my question is if i create Many Objects of SlowConstructor (let say 50 in diff threads) and as you can see each Constructor will take two hours to complete. The String reference in SlowConstructor unReachableString is not reachable from any code for around two hours. If GC runs during this two hours will it not collect unReachableString ref ?. I assume it will not be Garbage Collected but then why? From where unReachableString is reachable ?
The String reference in SlowConstructor unReachableString is not reachable from any code for around two hours.
Incorrect. The SlowConstructor object is immediately reachable from the thread that is in the process of constructing it. So, therefore, is the string.
So that means that the String object won't be garbage collected before the constructor completes.
(And in fact, the string object corresponds to a String literal, and is therefore also reachable from the code (any code!) that assigns or applies a method to the literal.)
The concept of reachability includes any mechanism by which any current or future execution could use the object in question. That includes cases where the object hasn't been assigned to a named variable or array element ... yet.
As other have said GC is not going to affect a half-constructed object. But why? GC necessarily proceeds from a maximal set of root pointers. Anything that can be reached from these roots is "protected" from GC. This is either my marking as in mark-and-sweep collectors or by copying to a new active generation (arena) in a copying collector. Roots consist of the runtime stack, machine (virtual or physical) registers, and global pointers. When the constructor starts running, a pointer to the newly allocated record will be created. Either it will be a root or accessible from a root. So the GC will not collect it. Since the class instance under construction is accessible from a root, so is the string you're referring to. Therefore it can't be collected either.
So long as the threads weren't interrupted, your object will (eventually) instantiate, and (eventually) contain a value for unReachableString.
Strings are interned, and would be subject to garbage collection only if nothing referred to it - kind of like how garbage collection works now. The half-constructed object does refer to the interned string, so it would not be yet eligible for garbage collection.
I'm willing to bet that having fifty or so instances of this type floating around* wouldn't make a difference either - you then have fifty or so references to this string literal, and it wouldn't be yet eligible for garbage collection until these instances were eligible for garbage collection themselves.
*: OH GOD NO PLEASE DON'T DO THIS IN ACTUAL CODE PLEASE
It will not and should not be garbage collected. Sleeping thread is still a live thread.
Reachable in GC context means the following: if we go through the Stack will we find a reference pointing to this object (memory space) on the Heap.
In you case the answer is yes.
your logic is not correct, if thread is still alive it is in scope of method SlowConstructor. So JVM thinks that unReachableString string can be used so Garbacge Collection does not touch that reference.
According to the code you can assume that unReachableString is not used so it has to be Garbage Collected but JVM does not have intelligent logic to know the next. It just look at the scope of method and object reference.

How to make sure String objects are garbage collected in Java

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. :-)

Java Assignment Memory Leaks

I have to assume that the following method doesn't leak memory:
public final void setData(final Integer p_iData)
{
data = p_iData;
}
Where data is a property of some class.
Every time the method gets called, a new Integer is replacing the currently existing data reference. So what's happening with the current/old data?
Java has to be doing something under the hood; otherwise we'd have to null-out any objects every time an object is assigned.
Simplistic explanation:
Periodically the garbage collector looks at all the objects in the system, and sees which aren't reachable any more from live references. It frees any objects which are no longer reachable.
Note that your method does not create a new Integer object at all. A reference to the same Integer object could be passed in time and time again, for example.
The reality of garbage collection is a lot more complicated than this:
Modern GCs tend to be generational, assuming that most objects are short-lived, so it doesn't need to check the whole (possibly large) heap as often; it can just check "recent" objects for liveness frequently
Objects can have finalizers - code to be run before they're garbage collected. This delays garbage collection of such objects by a cycle, and the object could even "resurrect" itself by making itself reachable
Modern GCs can collect in parallel, and have numerous tweaking options
Java is a garbage-collected language.
Once there are no more live references to an object, it becomes eligible for garbage collection. The collector runs from time to time and will reclaim the object's memory.
In a nutshell, your code is 100% correct and is not leaking memory.
It gets garbage collected eventually.
if there is no ther reference to data, the garbage collector of java will clean the old data up and free the memory
Actually, since Integer is an object not a primitive type, the line:
data = p_iData;
is updating a reference.
Now, the old object that this.data used to point to will be examined by the GC to determine if there are no more references to that object. If not, that object is destroyed and the memory is freed (at some later time)
If the object previously referenced by data is no longer referenced by any object structure that is referenced from any running thread it is eligible for garbage collecion. GC is performed by Java in the background to free the memory of unused objects.
i want to show one example to you
in some code :
int x;
x=10;
x=20;
initially i assigned x to 10
again x to 20
first reference memory will be handled by Java GC.
Java GC is a thread tht run continuously and checked unreferenced memory and clean it .

Categories

Resources