Java - Do object references get destroyed when the creating class is closed? - java

Say i have a class, which loads a file and then calls another method to do something to that file. For example, counting the words in the file.
Within class CountWords, a number of objects/collections are created in order to get the number of words. The method runs, the number of words is found, and then this is returned to the calling class.
My question is, do all the objects/collection created in the CountWords class get "destroyed" when control is returned to the calling class or do they remain in the memory? If the latter, would i have to set each object to null before exiting the class to mark them for collection?

We don't generally control exactly when a Java object gets destroyed. It will get destroyed some time after it becomes inaccessible - in other words, when there are no further references to it in any scope.
If you create an object, and store a reference to it in a field of another object, then the object you created continues to be accessible for as long as the object that has the reference to it is accessible.
If you have code like this
public void run() {
Foo a = new Foo();
System.out.println("This method is finished");
}
then the Foo that you created will be inaccessible as soon as run finishes, because there are no more variables with references to it. Foo will be destroyed some time afterwards. Unless of course, the constructor of Foo does some magic to register itself in some nasty static data store somewhere.
So in general, you don't need to go round setting references to null to destroy objects. From the point of view of the garbage collector, letting those references go out of scope is just as good as setting them to null.

Java is a programming language that has memory management aka garbage collection. The basic answer is, the garbage collector will take care of reclaiming the memory of unused objects.
But since you have tagged the question with [garbage-collection], you should already know this. So it’s not clear what additional detail you want to know or why you think your scenario is special in any way, to deserve an additional answer beyond “there is a garbage collector”.
You question is full of phrases that are wrong or misguiding.
“do object references get destroyed”—the storage of objects is reclaimed, there is no such thing as “destruction of references”
“when the creating class is closed”—there is no such thing as “closing of classes”
“do all the objects/collection created in the CountWords class get ‘destroyed’ when control is returned to the calling class or do they remain in the memory?”—in this form, not simple to answer
there is no such thing as “destruction”. The whole purpose of garbage collection is to permit the reuse of the memory. This implies recording somewhere that the memory is free. But the memory itself does not need to be touched.
when your method returns, these objects are eligible for garbage collection. The garbage collection itself does not have to run immediately. It may happen when there is need for free memory or when the CPU load is low.
As said, even if the garbage collector ran, the result is that the memory is now considered to be free, not necessarily to “scrub” the memory. So the objects may “remain in the memory” until actually being overwritten by other objects. So that’s simply the wrong question. You actually want to know whether the memory will be reusable.
“If the latter, would i have to set each object to null before exiting the class to mark them for collection?”—“the latter” still implies that the memory is free, semantically. But what do you want to “set to null”? The references do not exist anymore. The objects are unreachable.
The answer is there is nothing you can do and there is nothing you should do. That’s the whole point of garbage collection, no need for you to do anything.

We don't need to set the objects to null after coming out the function . For this Java have garbage Collector , which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.
For example :
for (int i =0 ; i<10 ; i++) {
String s = String.valueOf(i)
}
In the above code, the integer s is being created on each iteration of the for loop. This means that in every iteration, a little bit of memory is being allocated to make a integer object.
Going back to the code, we can see that once a single iteration is executed, in the next iteration, the integer object that was created in the previous iteration is not being used anymore -- that object is now considered "garbage".
Eventually, we'll start getting a lot of garbage, and memory will be used for objects which aren't being used anymore. If this keeps going on, eventually the Java Virtual Machine will run out of space to make new objects.
That's where the garbage collector steps in.
The garbage collector will look for objects which aren't being used anymore, and gets rid of them, freeing up the memory so other new objects can use that piece of memory.
Automatic memory management schemes like garbage collection makes it so the programmer does not have to worry so much about memory management issues, so he or she can focus more on developing the applications they need to develop.

Related

Unset instance when have few memory

I have a method that create some heavy objects as cache. This objects are rarely accessed, but expensive and slow to process, and are initialized only on demand. Then on use my application, for instance, I could request about three heavy object like that, and reuse them, but too is possible that I run it once and it only occupy memory while I never use it anymore during a session.
My question is: is possible I define that an object is "garbage collectable", then in case of application requires more memory it unset this unused data?
I think that it should works something like that (pseudo-code):
private static MyInstance instance = null;
public static getInstance() {
if (instance == null) {
instance = calculate();
GC.put(instance);
}
return instance;
}
I think that I can do it with some kind of Timer, then check from time to time, but I guess that Java should have something like that, to call only if memory is heavy used.
Yes, Java offers three types of indirect references which are sensitive to memory usage.
A cache can use a SoftReference that will be cleared before the process raises an OutOfMemoryError. As long as there is plenty of memory, however, the SoftReference will prevent its referent from being garbage collected.
Java does not have a way to manually de-allocate memory (see Memory Management in Java. However, it does have automatic garbage collection. This means that any object that has no references left in the program will be automatically removed. In your case, for example, if an Instance is no longer used (the function that used it returns, and no other references exist, or you overwrite the sole variable that stored a reference to the Instance with something else), that Instance will be garbage-collected.
There is not, however, any method of making the Instance disappear any faster than getting rid of references to it, and letting the garbage collector deal with it.
What I would suggest instead, for your application, is something like an LRU cache (see How would you implement an LRU cache in Java?), which would restrict your memory usage to a set number of instances, which (depending on what exactly Instance is) would limit you to a set amount of memory used by Instances.
If you wanted instead to allow any amount of memory to be used, but not used for very long, you could create a wrapper class for Instance, which implements your cache idea (only creates an Instance when called, if its current copy is null), but keeps a timer and sets its Instance to null after a given amount of time has expired without it being used.
What you need is a proper cache implementation. There are tons of them in Java, e.g., Guava Cache, which is highly configurable.
Your calculate method is just CacheLoader#load.
You don't need to care about the GC. Just size your cache properly so that not too much memory gets used. Evicted cache entries get collected automaticaly (when not referenced elsewhere).
I think that I can do it with some kind of Timer, then check from time to time, but I guess that Java should have something like that, to call only if memory is heavy used.
You can use time based eviction with e.g. CacheBuilder#expireAfterWrite. There's no caching in Java itself, but there's SoftReference. Anyway, I don't recommend using it directly, but consider using it with CacheBuilder#softKeys.

Java Finalizers, what tasks are really necessary

ArrayList<Object> foo;
Object[] bar;
typical finalizers will do
foo = null;
bar = null;
My question, will ArrayList call a finalizer wich sets any pointers it holds to null, or do I have to step through the list an do
for(i=1; i<foo.size(); i++) foo.set(i,null); ???
And the other question: for an array, do I need to set any of its contents to null, like
for(i=1; i<bar.length; i++) bar[i] = null;
or is it enough that the whole memory block is discarded and any pointer in it out of scope afterwards?
Sorry, if the question is stupid.
After reading through the answers I figured out, that there is nothing to implement there on your own.
Some sources suggest that if something like this (memory eating apps) happens, that this is by bad design.
My core question is: Doing often
struct = new LargeStructure();
does this exaust memory?
Or does this only need the memory of one of this structures?
BTW: The problem occours in a webapp running tomcat, and there is only one session active wich holds the described pointer as a session variable.
All objects will be eligible for GC by Garbage collector automatically when they are no longer referenced. You don't have to worry about it. If you are setting the array reference to null , then the array object itself is eligible for GC if there are no other live reference to the array object, the elements of the array will be eligible for GC if there are no live references to them anymore.
As per the documentation:
protected void finalize() throws Throwable
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
The finalize() method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object. If the object never becomes unreachable, or the GC doesn't run then finalize() may never be called.
You can try to force the JVM to call finalize() by calling System.runFinalization():
Runs the finalization methods of any objects pending finalization.
Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.
Theoretically finalizers let you perform last minute tasks on object before they are reclaimed by garbage collection. In practice however there is no guarantee that they will be called, so they are not very useful.
You don't have to set your object's references to null in finalizer block. Finalizer's are tipically used for last chance resource closing, it isn't a good practice, but finalizers can provide you a safety net for resource management.
My question, will ArrayList call a finalizer wich sets any pointers it holds to null, or do I have to step through the list an do
ArrayList will not call a finalizer, a finalizer thread will do that, but you don't have to worry about that. Also, you do not have to go over a list and finalize your elements your self. Java Garbage Collector will figure that one out for you and pick those objects up as long as they are not referenced anywhere else in the code.
And the other question: for an array, do I need to set any of its contents to null, like
No, same as above. Important thing to remember is that you have no reference to any value in the array, or to the array itself if you want it to be picked up by garbage collector.

Can objects destroy themselves? (Java)

We all know that the JRE will destroy any object that can no longer be referenced. But is there a way for an object to explicitly destroy itself? Or is that forbidden to avoid the dangling pointer problem?
Naively, I would like to say this = null, but that is disallowed by the compiler (this is probably not a true variable anyway).
Conversely, is there a way for an object to forcibly keep itself alive, by maintaining private copies of this, or otherwise?
No. In fact, you cannot forcibly destroy anything. Even if you have no references to an object, it will continue to exist in memory until the garbage collector decides to run and collect it.
You could keep an object alive by keeping a static reference to it.
Ignoring the academic aspect, you can't ensure an object is physically destroyed in Java (or most any other garbage collected language, like C#). This is because destroying objects is expensive (partly because of the memory compression phase), so the point is to run it as few times as possible.
This said however, you can force an object to release its allocated resources using the disposable pattern, where the object in question exposes a public method to release resources, and you can call it at any time (or it gets called automatically in the finalizer). It requires a bit more bookkeeping, but it gets the job done if really needed.
No you can't destroy an object.
What you could do is have a wrapper object that holds the actual object. If you make sure that nobody else has a reference to that object removing the reference (e.g. by setting it to null) will make the object qualify for the garbage collector. Note that it is still up to the GC to decide when and if to actually collect the garbage.
In order to keep an object alive you need to make sure that there is a reference to it. One way would be to have a static reference from the class of the object. As long as nobody unloads the class your object will stay in memory.
As you said I think it is forbidden to avoid dangling pointer problems. Java memory model is based on Stack and Heap model, if an object destroys itself then what would go to stack (or) other pointers, which references the object?

How to keep alive Java objects?

I'm just thinking about a way of keeping away Java objects from garbage collection even if it is not being referred for a reasonable amount of time.
How to do that?
Have a static container in your main class that you put a reference to the objects in. It can be a Map, List, whatever. Then you'll always have a reference to the object, and it won't be reclaimed. (Why you would want to do this is another question...)
Which is to say: As long as a reachable reference to an object exists, it will not be garbage-collected. If your code has a reference and tries to use it, the object will be there. You don't have to do anything special to make that happen (nor should you). (A reachable reference means that the reference is from something that is, itself, reachable from something other than the things it references. Put more simply: The GC understands about circular references and so can clean up A and B even if they refer to each other, as long as nothing else refers to either of them.)
[...] even if it is not being referred for a reasonable amount of time.
If there's any chance what so ever that an object will be accessed in the future, the object will not be garbage collected.
This is due to the fact that if you have a reference to the object, it won't be garbage collected, and if you don't have a reference to the object, there's no way you will be able to access it ever.
In other words, an ordinary reference will never mystically turn into a null just because the garbage collector observed that the object hadn't been accessed for a long time and thought it was time to reclaim it.
You could also create a static instance of the object in its own class. For example if it is a singleton, having a static instance field in the class.
There are mechanisms that will hold a reference to an object, but still allow it to be garbage collected, if there are no other references otherwise.
Look at WeakReference and SoftReference. If you want more details on reachability as far as the jvm is concerned, see:
http://download.oracle.com/javase/6/docs/api/java/lang/ref/package-summary.html#reachability
As far as time is concerned, the garbage collector doesn't know or care about how often an object is used. Either another object has a reference to the target (even if it's not using it), or there are no references to the target. If there are no references to the object, it could never be used again, and will eventually be freed (even if you wanted to, you couldn't obtain a reference to the object again) The longer-living an object is, the longer it takes for the jvm to free it, due to generational garbage collection.
I'm just thinking about a way of keeping away Java objects from garbage collection even if it is not being referred for a reasonable amount of time.
On the face of it, this question doesn't make sense. If an object is not referenced (or more a precisely, if it is not reachable) then the garbage collector will collect it. If you want to prevent an object from being garbage collected then you have to make sure that it is reachable. (Actually, it has to be strongly reachable to guarantee that it won't be GC'ed : see #Austen Holmes answer and the page that he references.)
But actually, I think that you are confusing "refered" / referenced / reachable with accessed or used; i.e. with the act of accessing a field or call a method of the object. If that is what you are asking, then I can assure that the garbage collector neither knows or cares whether your code has recently accessed / used an object.
The reachability criteria is actually about whether your code could access the object at some point in the future, and (therefore) whether the object needs to be kept so that this will work. The reachability rule means that if an object could be accessed, then it will be kept. It makes no difference how long it was since you last accessed it.

can any unused object escape from Garbage Collector?

Is there any possibility that a object which is not referenced anywhere and still existing on heap. I mean is there a possibility that a unused object getting escaped from garbage collector and be there on the heap until the end of the application.
Wanted to know because if it is there, then while coding i can be more cautious.
If an object is no longer referenced, it does still exist on the heap, but it is also free to be garbage-collected (unless we are talking Class objects, which live in PermGen space and never get garbage-collected - but this is generally not something you need to worry about).
There is no guarantee on how soon that will be, but your application will not run out of memory before memory from those objects is reclaimed.
However, garbage collection does involve overhead, so if you are creating more objects than you need to and can easily create less, then by all means do so.
Edit: in response to your comment, if an object is truly not referenced by anything, it will be reclaimed during garbage collection (assuming you are using the latest JVM from Sun; I can't speak toward other implementations). The reason why is as follows: all objects are allocated contiguously on the heap. When GC is to happen, the JVM follows all references to "mark" objects that it knows are reachable - these objects are then moved into another, clean area. The old area is then considered to be free memory. Anything that cannot be found via a reference cannot be moved. The point is that the GC does not need to "find" the unreferenced objects. If anything, I would be more worried about objects that are still referenced when they are not intended to be, which will cause memory leaks.
You should know that, before a JVM throws an out-of-memory exception, it will have garbage collected everything possible.
If an instance is no longer referenced, it is a possible candidate for garbage collection. This means, that sooner or later it can be removed but there are no guaranties. If you do not run out of of memory, the garbage collector might not even run, thus the instance my be there until the program ends.
The CG system is very good at finding not referenced objects. There is a tiny, tiny chance that you end up keeping a weird mix of references where the garbage collector can not decide for sure if the object is no longer referenced or not. But this would be a bug in the CG system and nothing you should worry about while coding.
It depends on when and how often the object is used. If you allocate something then deallocate (i.e., remove all references to it) it immediately after, it will stay in "new" part of the heap and will probably be knocked out on the next garbage collection run.
If you allocate an object at the beginning of your program and keep it around for a while (if it survives through several garbage collections), it will get promoted to "old" status. Objects in that part of the heap are less likely to be collected later.
If you want to know all the nitty-gitty details, check out some of Sun's gc documentation.
Yes; imagine something like this:
Foo foo = new Foo();
// do some work here
while(1) {};
foo.someOp(); // if this is the only reference to foo,
// it's theoreticaly impossible to reach here, so it
// should be GC-ed, but all GC systems I know of will
// not Gc it
I am using definition of: garbage = object that can never be reached in any execution of the code.
Garbage collection intentionally makes few guarantees about WHEN the objects are collected. If memory never gets too tight, it's entirely possible that an unreferenced object won't be collected by the time the program ends.
The garbage collector will eventually reclaim all unreachable objects. Note the "eventually": this may take some time. You can somewhat force the issue with System.gc() but this is rarely a good idea (if used without discretion, then performance may decrease).
What can happen is that an object is "unused" (as in: the application will not use it anymore) while still being "reachable" (the GC can find a path of references from one of its roots -- static fields, local variables -- to the object). If you are not too messy with your objects and structures then you will not encounter such situations. A rule of thumb would be: if the application seems to take too much RAM, run a profiler on it; if thousands of instances of the same class have accumulated without any apparent reason, then there may be some fishy code somewhere. Correction often involves explicitly setting a field to null to avoid referencing an object for too long.
This is theoretically possible (there is no guarantee the GC will always find all objects), but should not worry you for any real application - it usually does not happen and certainly does not affect a significant chunk of memory.
In theory, the garbage collector will find all unused objects. There could, of course, be bugs in the garbage collector…
That said, "In theory there is no difference between theory and practice, in practice, there is." Under some, mostly older, garbage collectors, if an object definition manages to reach the permanent generation, then it will no longer be garbage collected under any circumstances. This only applied to Class definitions that were loaded, not to regular objects that were granted tenured status.
Correspondingly, if you have a static reference to an object, that takes up space in the "regular" object heap, this could conceivably cause problems, since you only need to hold a reference to the class definition from your class definition, and that static data cannot be garbage collected, even if you don't actually refer to any instances of the class itself.
In practice though, this is a very unlikely event, and you shouldn't need to worry about it. If you are super concerned about performance, then creating lots of "long-lived" objects, that is, those that escape "escape-analysis", will create extra work for the garbage collector. For 99.99% of coders this is a total non-issue though.
My advice - Don't worry about it.
Reason - It is possible for a non-referenced object to stay on the heap for some time, but it is very unlikely to adversely affect you because it is guaranteed to be reclaimed before you get an out of memory error.
In general, all objects to which there are no live hard references, will be garbage-collected. This is what you should assume and code for. However, the exact moment this happens is not predictable.
Just for completeness, two tricky situations [which you are unlikely to run into] come into my mind:
Bugs in JVM or garbage collector code
So called invisible references - they rarely matter but I did have to take them into account one or two times during the last 5 years in a performance-sensitive application I work on

Categories

Resources