Java final vs Py __del__

Jay O'Connor joconnor at cybermesa.com
Thu Nov 27 12:44:44 EST 2003
Kepes Krisztian wrote:

>Hi !
>
>I very wonder, when I get exp. in java with GC.
>
>I'm Delphi programmer, so I get used to destructorin objects.
>
>In Java the final method is not same, but is like to destructor (I has
>been think...).
>
>And then I try with some examples, I see, that the Java GC is
>sometimes not call this method of objects, only exit from program.
>So: the java programs sometimes end before the GC is use the final
>methods on objects.
>
>This mean that in Java the critical operations MUST do correctly by
>the programmmers, or some data losing happened.
>If it is open a file, then must write the critical modifications, and
>must use the flush, and close to be sure to the datas are saved.
>
>In the Py the __del__ is same java's final, or it is to be called in
>every way by GC ?
>
>I build this method as safe method: if the programmer don't do any
>closing/freeing thing, I do that ?
>
>simple example:
>
>class a:
>      def __init__(self,filename):
>          self.__filename=filename
>          self.__data=[]
>          self.__file=None
>      def open(self):
>          self.__file=open(self.__filename,"w")
>      def write(self,data):
>          self.__data.append(data)
>      def close (self):
>          self.__file.writelines(self.__data)
>          self.__file.close()
>          self.__file=None
>      def __del__(self):
>          if self.__file<>None:
>             self.close()
>          # like destructor: we do the things are forgotten by
>          programmer
>
>Thanx for infos:
> KK
>

Generally, in langauges that use GC, you should not use the GC for 
resource management such as file handles, database connections, graphics 
contexts, etc..  Partially because you can't really determine when/if 
they will be called.  Partially because if you are dealing with a 
limited resource, then you need to be managing the use of that 
resource.  The only resource you should rely on the GC to manage is memory.

For what it's worth, Python allows the registering of a callback 
function that will be called by the VM when the system is about to shut down





More information about the Python-list mailing list