How can I delete object manually in Java? Is there any method like obj.delete() or obj.kill()
There is no real way. Java has a special Garbage Collector which does that for you. Once your object doesn't have any references to it, it will be picked up by the Garbage Collector at some point and destroyed.
From Learning Java Tutorials:
The Garbage Collector
An object is eligible for garbage
collection when there are no more
references to that object. References
that are held in a variable are
usually dropped when the variable goes
out of scope. Or, you can explicitly
drop an object reference by setting
the variable to the special value
null. Remember that a program can have
multiple references to the same
object; all references to an object
must be dropped before the object is
eligible for garbage collection.
There is no way to delete an object. Java's Garbage Collector will do it automatically when an object has no more references.
You can however run the Garbage Collector once you have removed all references to an object by calling System.gc(). Please do read the method's documentation carefully. It only guarantees best-effort to delete all objects marked for deletion.
You should also go through these discussions
Java memory management best practices
Java finalize method call
One of the main reasons for Java being so popular is the Garbage Collection. You do not have to worry about allocating or deallocating memory. That being said if you want to get rid of an object just set all references to the object to null and once the garbage collector runs the object will be disposed of.
You do have to worry about closing resources such as files, sockets, database connections etc... and for that you should do it in a try/finally block.
just assign the null value to it.
Let GC take care of this
obj = null;
Related
I'd like to use a WeakReference as a more efficient finalize() method, for the purpose of freeing native resources associated with an object as soon as it becomes possible to do so, without using finalization (which has significantly higher costs than using a WeakReference).
Since this is the only purpose of the WeakReference (I will never use the WeakReference to obtain the referenced object), it seems wasteful to take the time and space to maintain a list of my WeakReferences to prevent them from being garbage collected.
But if a normal object is constructed and no strong reference is kept to it, it will simply be freed by the garbage collector, and I can't find anything in the Javadoc that suggests this is different for a WeakReference.
Is it necessary to keep a reference to a WeakReference to prevent it from being garbage collected, or, if it's to be enqueued in a ReferenceQueue, will that keep it alive until it's been collected from the queue?
Is it necessary to keep a reference to a WeakReference to prevent it from being garbage collected
Have a look at the java.lang.ref package description, it dedicates a whole paragraph to answering your question:
The relationship between a registered reference object and its queue is one-sided. That is, a queue does not keep track of the references that are registered with it. If a registered reference becomes unreachable itself, then it will never be enqueued. It is the responsibility of the program using reference objects to ensure that the objects remain reachable for as long as the program is interested in their referents.
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.
Garbage collection identify the objects that are no longer referred to by any variable and then reclaims the memory occupied by the objects.
I don't whether this process is done in a regular interval or as soon as an objects reference count falling down to zero.
suppose, if GC works immediately whenever an objects reference count falling down to zero then there is no need for requesting GC by calling System.GC();So, what is purpose of this method in this case?
GC is neither done in a regular interval nor as soon as an objects reference count falling down to zero (Note: that most JVM implementations do not use a reference counting algorithm, so this last point is moot).
When GC will run is decided by The garbage collection algorithm.
When you call System.gc(), you say to the garbage collector to make a clean-up. The problem is that it isn't clear when the GC will respond to your request. Even more, it is possible that GC to not run at all when you call it. In java you cannot predict how the GC will work. (That's why is considered bad practice to put your cleanup code in Object's finalize() method). In Java, the out of reference objects are collected for garbage automatically. That's why you don't need to call System.gc(). In special cases, when you want run it if possible, you can try to make use of this method, but the behavior is not guaranteed. (as specified above).
Most modern JVMs use a "stop-the-world" garbage collector, that is a garbage collector that stops all the application threads in the program, performs the garbage collection, and then resumes the application threads. This means that before doing the garbage collection, all threads in the application should reach a point that is safe to stop the thread.
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. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection.
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.
There are two answers:
It is not specified by the JVM spec, the JLS or any of the other definitive Java documents when the garbage collector will run. It is therefore implementation specific.
In practice, a couple of different strategies are commonly used. For a non-concurrent collector, the GC is triggered when an attempted allocation fails because there isn't enough unallocated space. For a concurrent collector, a collection is started when the amount of free space falls below a pre-determined threshold. (For HotSpot concurrent GC's, the threshold ratio is a tunable parameter.)
No modern Java GC uses reference counts.
The purpose of the System.gc() is to allow an application to give the JVM a hint that "now would be a good time to run the garbage collector". The JVM is allowed to ignore that hint. As a general rule, triggering the GC that way is inefficient in terms of CPU usage. The only legitimate reason to do it in production code is as a way to avoid GC pauses in a highly interactive application. (You try to force a GC at a point when you know that interactivity is not required; e.g. between "levels" in a game.)
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.
I have a HashMap (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected?
If I do map.clear() and those objects that were in the table are not referenced anywhere else, will they get garbage collected?
What is the fastest way, to actually remove all entries from the table, but also destroy those objects.
Yes, if the collection is the last place these objects are referenced they are eligible for garbage collection after they have been removed from the collection. And no, you can not destroy these objects forcefully. The garbage collector will handle them when it feels like it.
If the only remaining reference to the object is in this table, then will the object get garbage collected?
If there are no other references to an object, then the object will be garbage collected sometime in the future.
You should not have to force destruction of the objects. If they are extremely heavyweight objects (or you have too many objects to fit in memory), this points to a more fundamental problem with your code.
If you really must, then you can call System.gc(), although this is not good practice, and will always be a bellwether of underlying problems in your code.
Generally speaking, you have no strong control over when an object is specifically destroyed. Any object is eligible for garbage collection when there are no more (strong) reference to it - but there are no guarantees about when it will be garbage collected or in fact if it ever will be. Even calling System.gc() or Runtime.gc() provides no guarantees about actually doing anything, it's merely a hint to the JVM that it might want to consider garbage collecting now. I believe the only guarantee you get is that if an OutOfMemoryError is thrown, all potential garbage collections were done before the error was thrown.
There are implications here for handling sensitive information such as passwords. Since Strings cannot be programatically cleared, you ideally don't want to store the password as such. If you instead store it as an array of characters, you can then use Arrays.fill(' ') to overwrite the password and guarantee it is no longer resident in memory from that point.
Back back on topic - you are right that both operations will make the object eligible for garbage collection if it is not being referenced elsewhere. Collection.clear() is indeed the fastest way to drop references to all the objects in a collection at once.
Note that WeakHashMap allows you to place objects in it and have them eligible for garbage collection as soon as there are no more references to the key (not the value) outside the map - the map entry will disappear at this point.
In general you should not worry about when objects are garbage collected - the JVM decides this, and it knows a lot more about its memory needs and possible delays than you. What you should worry about is to make sure that objects you don't need anymore are eligible for garbage collection.
To have something truly garbage collected there can be no Strong references to the object. Objects with weakReference's may be garbage collected. Use WeakHashMap to make sure they are garbage collected, as that in a HashMap there is still references to the object.
You can initiate a call to System.gc() after you clearyour map, but it's generally not a good idea.