Android: insert into database while an entity is invoking finalize

47 views Asked by At

I need to store user name and avatar url as much as possible for other using, so I insert into database in the finalize function of the userinfo entity. Is it bad or has any problem do like this, as I thought finalize is invoked when an object is going to be collect by the gc so it is bad to do anything there.

code:

enter image description here

enter image description here

1

There are 1 answers

0
Nicolas Filotto On BEST ANSWER

Yes generally speaking, it is a bad practice to implement a finalizer as it will slow down the garbage collection, especially in your case as you insert something into the database which is a slow operation. So imagine that the GC does a stop-the-world and you have many instances of this object to be collected, your application will be unusable for a longer period of time.

Please also note that a finalizer should be implemented into a try/finally block to ensure that the finalizer of the super class is called whatever happens, as next:

@Override
protected void finalize() throws Throwable {
    try {
        // Something here
    } finally {
        super.finalize();
    }
}