Search code examples
javasqldatabasedestructorresource-cleanup

Java resource clean up before object destruction


I've the following problem and I know there are already a lot of questions but none of these give me really a satisfactorily answer! I wrote a lot of stuff in C++ and this language provide a destructor, Java doesn't because of the garbage collection.

A little introduction in my situation: I wrote a software which is accessing a local Sqlite3 database. I wrote a central singleton class for accessing this database. Multiple other classes access the DB through this wrapper class. Here is the pseudo-code of this wrapper class:

public class MyDbWrapper
{
    private currentDbConnection;

    public MyDbWrapper(dbPath)
    {
        // Open the database connection with given path
    }

    public readFromDb()
    {
        ... // Uses the class member currentDbConnection
    }

    public writeToDb()
    {
        ... // Uses the class member currentDbConnection
    }

    public closeDb()
    {
        ...
    }
}

Now my question is, how could I ensure that the database connection is closed before quitting the application? Yes I already implemented the AutoCloseable interface and yes I worked already a lot with try-with-resources, but because of the access by multiple classes this isn't really an option! In C++ a destructor would solve this issue, but the possible "equivalent" in java the method finalize is deprecated!

So are there any other options or should I totally re-design my complete wrapper? If yes, how could I prevent performance issues because of a lot of read write access if I re-open the database every time?


Solution

  • Like Joker_vD already said, I solved this issue by using a try-with-resources statement in the main method of my program...

    public static void main(String [] args)
    {
        try(MyDbWrapper wrapper = new MyDbWrapper())
        {
            // Execute other task with usage of the database wrapper
        }
    }
    

    With this solution there is no need for a desturctor or the usage of the deprecated method finalize(), the database connection get closed if program ends...

    Thanks again and credits to Joker_vD