• Post Reply Bookmark Topic Watch Topic
  • New Topic

Best way to release memory  RSS feed

 
Arun Kumar
Ranch Hand
Posts: 135
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

There is a confusion in our team as teh teh best way to release the memory objects from an Arraylist

Suppose we have an arraylist 'aList' containig lot of objects,which one of the below process is best



OR


Method close()







 
Adam Michalik
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

So to clarify: there is a list L containing records R, each record has two member variables: A and B. If you set the L reference to null, the whole graph of objects (L -> multiple Rs -> A, B) becomes an unreachable island and can be garbage collected. So setting each reference to null is not necessary, and even undesirable as it's additional effort of your code, which can be easily done by the garbage collector. This attitude has an additional advantage - if L, Rs, As or Bs are referenced from somewhere else, they will be preserved. Using the "nullifying" solution if you did R.close() in this place (setting R.A and R.B to null) and had a reference to R in another place and wanted to do something with R.A, you'd get a NullPointerException. Leaving this to the garbage collector is much safer and cleaner.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the close() method was necessary for cleaning up system resources (e.g. streams, database connections, etc), then you would need to call close() on each element first, then null the list reference. As Adam said, simply nulling fields in a close() method is not appropriate.
 
Arun Kumar
Ranch Hand
Posts: 135
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob and Adam for your valuble comments
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!