473,788 Members | 2,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java final vs Py __del__

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,f ilename):
self.__filename =filename
self.__data=[]
self.__file=Non e
def open(self):
self.__file=ope n(self.__filena me,"w")
def write(self,data ):
self.__data.app end(data)
def close(self):
self.__file.wri telines(self.__ data)
self.__file.clo se()
self.__file=Non e
def __del__(self):
if self.__file<>No ne:
self.close()
# like destructor: we do the things are forgotten by
programmer

Thanx for infos:
KK


Jul 18 '05 #1
2 1644
Kepes Krisztian <Ke************ *@peto.hu> wrote in
news:ma******** *************** **************@ python.org:
In the Py the __del__ is same java's final, or it is to be called in
every way by GC ?
There is more than one implementation of Python. In C Python, __del__ will
be called as soon as there are no more references to the object, but the
Java implementation of Python will never call __del__ until the object is
garbage collected.

Even in removing the last reference to an object, which causes __del__ to
be called can happen in a slightly suprising way. Usually a variable going
out of scope would be sufficient to release the object it referred to
(assuming of course there are no other references to the same object), but
if a function throws an exception, the objects referenced by the local
variable will have their lifetimes extended, typically until the next time
an exception is thrown (which probably happens in a completely unrelated
function). The garbage collector can also cause objects to be released by
collecting the objects which kept them alive, but if an object that
participates directly in a cycle has a __del__ method then it will never be
garbage collected, so its __del__ will never be called.

When Python exits, it does its best to ensure that all objects are released
in an orderly manner, but sometimes that just isn't possible. So some
objects may not get their __del__ methods called on program exit, and other
objects may find that when __del__ is called, there are no other objects
around for them to reference.

I build this method as safe method: if the programmer don't do any
closing/freeing thing, I do that ?
No, this won't work reliably. If you want to do this, look at the atexit
function.

simple example:

class a:
def __init__(self,f ilename):
self.__filename =filename
self.__data=[]
self.__file=Non e
def open(self):
self.__file=ope n(self.__filena me,"w")
def write(self,data ):
self.__data.app end(data)
def close(self):
self.__file.wri telines(self.__ data)
self.__file.clo se()
self.__file=Non e
def __del__(self):
if self.__file<>No ne:
self.close()
# like destructor: we do the things are forgotten by
programmer

Thanx for infos:


What I would suggest you do here, is something like (this is untested code,
so it may have errors):

import weakref
import atexit

ObjectsToClose = weakref.WeakVal ueDictionary()

def CloseObjects():
try:
while true:
key, o = ObjectsToClose. popitem()
o.close()
except:
pass

atexit.register (CloseObjects)

class a:
def __init__(self,f ilename):
self.__filename =filename
self.__data=[]
self.__file=Non e
ObjectsToClose[id(self)] = self
... rest of class a goes here ...

This code will ensure that the close method gets called on each of your
objects when the program exits (unless you are running on Windows and the
user uses control+break to kill the program --- if you are then you'll need
some additional code to ensure that atexit gets called correctly).

The WeakValueDictio nary will automatically remove from itself any objects
which are destroyed before the program closes.

--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #2
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,f ilename):
self.__filename =filename
self.__data=[]
self.__file=Non e
def open(self):
self.__file=ope n(self.__filena me,"w")
def write(self,data ):
self.__data.app end(data)
def close (self):
self.__file.wri telines(self.__ data)
self.__file.clo se()
self.__file=Non e
def __del__(self):
if self.__file<>No ne:
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

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
10850
by: Fu Bo Xia | last post by:
the java.lang.Object.forName method takes a java class name and returns a Class object associated with that class. eg. Class myClass = Object.forName("java.lang.String"); by if i only know the absolute file name of a .class file eg. C:\myJava\myApp.java, then how do i translate this file name to a java class name the Object.forName method would accept has it's parameter? thanks,
6
2594
by: Peter Abel | last post by:
I have an application, which is an instance of a class with a deeply nested object hierarchy. Among others one method will be executed as a thread, which can be stopped. Everything works fine except that when deleting the main instance - after the thread has been stopped - the __del__ method will not be carried out. Tough a simple example works as expected: >>> class A: .... def __init__(self):
13
2037
by: Emmanuel | last post by:
Hi, I run across this problem, and couldn't find any solution (python 2.2.2) : Code : =========== from __future__ import generators >>> class titi:
1
2028
by: schwerdy | last post by:
Hello developers! I'm using Python 2.3.4 under debian Sarge and want to write a small logger class. My source code reads: #*************************************************** import sys, time from fcntl import * class Log(object): """
1
1490
by: Erwan Adam | last post by:
Hello all, Can someone reproduce this bug ... I use : python Python 2.4.3 (#2, Sep 18 2006, 21:07:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. First test :
2
3982
by: astolpho | last post by:
I am using a slightly outdated reference book on J2EE programming. It gives 2 methods of creating a database used in its casestudies. The first is an ANT script that gives the following output: D:\original\CaseStudy-2-5\CaseStudy\Day02\exercise>asant database Buildfile: build.xml env-user: prop-user: set-user:
5
6292
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is JDK 6 downloadable from http://java.sun.com/javase/downloads/index.jsp. I will be using JDK 5(update 8)
6
2875
by: George Sakkis | last post by:
I'm baffled with a situation that involves: 1) an instance of some class that defines __del__, 2) a thread which is created, started and referenced by that instance, and 3) a weakref proxy to the instance that is passed to the thread instead of 'self', to prevent a cyclic reference. This probably sounds like gibberish so here's a simplified example: ==========================================
2
3767
by: yeshello54 | last post by:
so here is my problem...in a contact manager i am trying to complete i have ran into an error..we have lots of code because we have some from class which we can use...anyways i keep getting an error when i do the following. if you add a contact with up to 13 fields it will be stored in a data structure. i have a tabbed pane that will show six of the 13 fields for that contact. when you double click the contact i want it to pop up and show all 13...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5403
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2897
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.