calling finalize() on db objects

17 views
Skip to first unread message

howud...@gmail.com

unread,
Feb 15, 2017, 10:32:52 PM2/15/17
to CodenameOne Discussions
I am getting the following errors on Database object that "supposedly" hasn't been closed yet.  I have a helper class that I use to retrieve the Database (all db calls go through this class) and in it's finalize I call close() on the db.  you can see from my log that it is being called.  Interestingly if I sprinkle my code with System.gc() I never get the warnings, only my Created/Finalized messages.

 I'm not sure what I am doing wrong
MySQLiteDatabase Created:com.myapp.db.MySQLiteDatabase@7e9eb29
MySQLiteDatabase Created:com.myapp.db.MySQLiteDatabase@35618bac
MySQLiteDatabase Created:com.myapp.db.MySQLiteDatabase@5d07ff0
**** WARNING! Database object was released by the GC without being closed first! This might cause crashes on iOS *****
MySQLiteDatabase Finalized:com.myapp.db.MySQLiteDatabase@5d07ff0
MySQLiteDatabase Finalized:com.myapp.db.MySQLiteDatabase@35618bac
**** WARNING! Database object was released by the GC without being closed first! This might cause crashes on iOS *****
MySQLiteDatabase Finalized:com.myapp.db.MySQLiteDatabase@7e9eb29

Here is the class that I use to wrap all my db calls:
public class MySQLiteDatabase extends Object {
 
protected Database db = null;
 
 
public void setDb(Database db) {
   
this.db = db;
 
}
 
 
public MySQLiteDatabase() {
   
System.out.println("MySQLiteDatabase Created:" + this);
 
}
 
 
protected void finalize() throws Throwable {
   
System.out.println("MySQLiteDatabase Finalized:" + this);
   
try {
     db
.close();
   
} catch (IOException e) {
     e
.printStackTrace();
   
}
 
}
... }


Peter 

Shai Almog

unread,
Feb 16, 2017, 12:09:54 AM2/16/17
to CodenameOne Discussions, howud...@gmail.com
Never override finalize().
You need to close connections properly on the same thread where they were opened. Finalize is invoked on the GC thread.
Reply all
Reply to author
Forward
0 new messages