• Post Reply Bookmark Topic Watch Topic
  • New Topic

Destroying objects - I should know this one !  RSS feed

 
Nathan Russell
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, before I start, I know I should know the answer to this as I've recently passed my SCJP, and its pretty fundamental stuff ! But here goes anyway ...

Should I destroy any object I create after use, and will I suffer memory leaks if I dont ?

My scenario is this. I have written a couple of JSP pages (I know this is not the JSP section, but I dont think this is a JSP question). Within the JSP pages I instantiate and use certain objects. I have noticed that the memory usage of the JVM on the host server is continually increasing up to a point where it throws out of memory exceptions and wont work any longer !
So, do I need to explicitally destroy the object after use ?
For example, at the moment, I might do something very simple like:

At the moment I don't explicitally destroy the someObj object.
Do I need to do someObj=null; after I've finished with it ?

Assuming that Yes, I should destroy my objects after use; lets say that in the JSP file I am actually creating and using some other class (myBook) - a class that I have created that internally might be using String, Vector etc
If I need to explicitally destroy the myBook object after use, do I also need a finalize() method in the myBook class that explicitally destroys the objects that it used internally ?

Sorry if these are dumb questions - like I said in the preamble, I should know better !

Cheers

Nathan
 
Satish Chilukuri
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMO, there is no need to explicitly destroy an object to free up memory. As long as you make sure that the object doesn't have any references beyond the intended scope, it will be eligible for garbage collection once the scope is exited.

The code sample you've given looks fine to me. The someObj goes into the jspService() method and when the container finihses executing that method, someObj is eligible for garbage collection. One reason for those OutOfMemory errors could be that you add an object to ServletContext or Session, but forget to remove it when you are done with using it.

[EDIT]I believe you cannot destroy an object. You can only suggest the JVM that it do so.
[ May 23, 2006: Message edited by: Satish Chilukuri ]
 
mohit bahl
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nathan
Destroying objects (setting them to null for garbage collection) is a good practice. Whenever you think that your code will be creating lots of objects then it will be efficient to set them to null.
in case of JSPs you can investigate the class file that is created for it to see how many objects are created which will help you to do things better in your JSP. Rest i think your container will take care.

When you are setting your object to null which in turn uses other objects, those objects are also set for garbage collection unless there is some object which is shared between your object (which is set to null) and another object which is currently active. Such cross references can cause a delay in garbage collection.

if you are facing some memory performance issue then do share the piece of code.

cheers
mohit
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This thread contains misleading information. You cannot set objects to null - ever. You can however, set references to null. Doing so is a poor practice - in fact, the very existence of null is a workaround to the flaws of the "OO paradigm" (implicit exposure of invalid order of invocation of contractual operation, or as some people put it, lack of first-class functions, but let's not go there ).

Setting references to null often occurs for reasons other than you have stipulated - usually because of a misunderstanding of how to use scope and definite assgnment semantics. There is never a good reason to assign a reference to null, and more so, there is even less of a reason to set a reference to null in some vain attempt to "free objects" or somehow "help the garbage collector".

[Removed parts of post that violated our "Be Nice" rule - GDB]
[ May 23, 2006: Message edited by: Gregg Bolinger ]
 
Nathan Russell
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tony Morris:
This thread contains misleading information. You cannot set objects to null - ever. You can however, set references to null. Doing so is a poor practice - in fact, the very existence of null is a workaround to the flaws of the "OO paradigm" (implicit exposure of invalid order of invocation of contractual operation, or as some people put it, lack of first-class functions, but let's not go there ).

Setting references to null often occurs for reasons other than you have stipulated - usually because of a misunderstanding of how to use scope and definite assgnment semantics. There is never a good reason to assign a reference to null, and more so, there is even less of a reason to set a reference to null in some vain attempt to "free objects" or somehow "help the garbage collector".

[Removed not nice quote - GDB]


Blimey ! and there was me thinking I could ask a question and get a helpful answer !
Removed Not Nice Quote - GDB

Very true, but then I did acknowlegde this in the preamble of my original post. I believe this to be fundamental; but its not actually covered in the SCJP - not to the extent that I am asking anyway.
Garbage collection is covered, finalize() is covered to a degree, and understanding the scope of objects that you may create - its all covered; and presumably I understand it sufficiently to score 72%
But what is not covered is your view that the reference to objects should never be set to null
Its an interesting train of thought though. If we should never set the reference of an object to null; what would you use the finalize() method for ? My understanding is tidying up, clearing down resources (destroying objects ? ) etc in a controlled manner. But then if the code was written properly in the first place, would you need it ?
If for example you had a class with a method that opened a file, or a database connection, I would close the file or db as part of the method that used it. I certainly would not close such resources in finalize() as you cant guarantee when it will run ?

Interesting subject though .....
[ May 23, 2006: Message edited by: Gregg Bolinger ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you suggest, finalize is unreliable and I would simply never use it at all.

I have seen folks set references to null in hopes of making objects available for GC earlier, but trying to be smarter than the GC is futile. If you're holding objects very long after you're really done with them there is likely something else wrong with the scoping in your design.

Your memory increase over time may be perfectly normal. It's not really a problem until you use up the heap and fail to allocate objects. We got a nifty monitor and started to panic when we saw heap jump from 20% used to 40% used. Took a while to realize we didn't need to care until over 80%.

Or it may be a real leak - references that never become eligible for GC. In JSP/Servlet code a good place to leak is the session. Maybe you put a Collection on the session and add something to it on every page but never remove any? Another good place is home-made caching. Maybe you cache the results of every database call and never clean them up? These are only the things I've done myself. I'm sure there are many more.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was never any intent to be "not nice". I struggle to see how it could be interpreted that way.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nathan Russell:

Its an interesting train of thought though. If we should never set the reference of an object to null; what would you use the finalize() method for ? My understanding is tidying up, clearing down resources (destroying objects ? ) etc in a controlled manner. But then if the code was written properly in the first place, would you need it ?
If for example you had a class with a method that opened a file, or a database connection, I would close the file or db as part of the method that used it. I certainly would not close such resources in finalize() as you cant guarantee when it will run ?


Are you confused over try-catch-finally and finalize? These are pretty different stuffs. When we do file I/O or DB related stuffs, the clean-up is normally done inside the finally block. Of course, if the JVM crashes, or someone tripped over the power cord, nothing gets run.
[ May 24, 2006: Message edited by: Chengwei Lee ]
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a frequently made mistake by developers that could lead to performance issues related to memory leaks & garbage collection. Suppose you've a couple database CRUD to perform, and these need to be done repeatedly for a finite amount of times. Most people would put them inside a for-loop, and use the String variable to formulate your SQL queries.

If this piece of codes get executed often enough, and the iterations is significantly big per execution, we end up creating many short-lived String objects. The poor JVM would be busy with performing GC on these short-lived objects.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought short lived objects put little or no strain on the GC!

Check out Brian Goetz's thoughts on this: http://www-128.ibm.com/developerworks/java/library/j-jtp09275.html
His advice is "Go on, make a mess".
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chengwei Lee:
There's a frequently made mistake by developers that could lead to performance issues related to memory leaks & garbage collection. Suppose you've a couple database CRUD to perform, and these need to be done repeatedly for a finite amount of times. Most people would put them inside a for-loop, and use the String variable to formulate your SQL queries.

If this piece of codes get executed often enough, and the iterations is significantly big per execution, we end up creating many short-lived String objects. The poor JVM would be busy with performing GC on these short-lived objects.


No. As Goetz points out, the cost is virtually free and it's entirely possible it will be optimized away entirely. Not to mention the fact that chances are the time spent in allocating and recovering memory in your scenario is probably microscopic compared to the time spent compiling the SQL queries and executing them.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tony Morris:
This thread contains misleading information. You cannot set objects to null - ever. You can however, set references to null. Doing so is a poor practice - in fact, the very existence of null is a workaround to the flaws of the "OO paradigm" (implicit exposure of invalid order of invocation of contractual operation, or as some people put it, lack of first-class functions, but let's not go there ).

Setting references to null often occurs for reasons other than you have stipulated - usually because of a misunderstanding of how to use scope and definite assgnment semantics. There is never a good reason to assign a reference to null, and more so, there is even less of a reason to set a reference to null in some vain attempt to "free objects" or somehow "help the garbage collector".

[Removed parts of post that violated our "Be Nice" rule - GDB]

[ May 23, 2006: Message edited by: Gregg Bolinger ]


Tony there is at least one situation where setting a reference to 'null' isn't a bad thing. When an Object with a long lifespan has a reference to an Object that will never be used by the program again setting the reference to null isn't a bad thing. HOWEVER, I'm pretty sure you're going to say that such a situation is merely a symptom of poor design, excessive scope, etc. While I don't necessarily disagree the fact of the matter is that nobody is perfect and in the real world we have to work with colleagues who are significantly less than perfect. When that situation arises, regardless of why or whose fault it is, you have two choices. Either fix the flaws that led to the problem or deal with it by cutting off the fat with null references and sometimes you simply aren't in a position to fix it.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tony there is at least one situation where setting a reference to 'null' isn't a bad thing. When an Object with a long lifespan has a reference to an Object that will never be used by the program again setting the reference to null isn't a bad thing. HOWEVER, I'm pretty sure you're going to say that such a situation is merely a symptom of poor design, excessive scope, etc. While I don't necessarily disagree the fact of the matter is that nobody is perfect and in the real world we have to work with colleagues who are significantly less than perfect. When that situation arises, regardless of why or whose fault it is, you have two choices. Either fix the flaws that led to the problem or deal with it by cutting off the fat with null references and sometimes you simply aren't in a position to fix it.

I agree entirely - I spend most of my days dealing with broken code. There is no "good reason" (within our assumed context of "software") to assign to null - this has been known by quite a lot of people for years.

However, it's important to portray the truth as best as you can particularly when a naive audience (i.e. beginner's forum) is requesting that information with a degree of trust in your response. How I deal with The Brokenness(TM) is another matter entirely and in fact, there are optimal workarounds to most of the intrinsic flaws of the language and the common abuses of it. Someone should write a book. Funny, I had a very similar conversation yesterday with a colleague
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!