1

I build an app that uses SQLiteOpenHelper and I see that the cursor objects I received from the queries are closing themselves in their finalize methods.

I know it's not recommended to rely on the finalize method but if I'm working right and not keep unnecessary references to any object (in singletons, lists, async-tasks etc) can't I be sure that all my cursor objects will be released (after an activity or fragment destroyed)?

Bokris Itzhak
  • 911
  • 9
  • 30

1 Answers1

3

I know it's not recommended to rely on the finalize method

Good, because that's exactly why it's being closed prior to the finalize clause.

In reference to Effective Java: "Never depend on a finalizer to update critical persistent state" because "one shortcoming of finalizers is that there is no guarantee they’ll be executed promptly".

Since closing a connection is changing persistent state (with regards to the DB), you should be closing prior to the finalizer.

Also, cursor objects aren't "released" automatically. The database itself is "cached", so whether or not the object itself is released doesn't change the database's state. Check out this question for more details.

Community
  • 1
  • 1
Jared Hooper
  • 881
  • 1
  • 10
  • 31
  • 1
    Not only there is no guarantee the finalizer will be executed promptly, there is no guarantee it will be executed at all. At shutdown, the JVM doesn't execute the finalizer of the still alive objects. – Kazaag Feb 01 '16 at 10:07
  • Jared, can you explain how "closing a connection is changing persistent state (with regards to the DB)"? What persistent state gets changed by closing a cursor? – LarsH Sep 25 '17 at 13:21
  • @Kazaag: True, but if your process gets shutdown, does it matter anymore if some cursors didn't get closed? Not that I know of, but there may be important things that I'm ignorant of, so I'd like to find out. – LarsH Sep 25 '17 at 13:22
  • 1
    If you are connected on a remote server, the server is not properly notify that the connection is over. If you are dealing for local storage, you may end up is a non expected state (not all state flushed, some missing index, lock files still present...). – Kazaag Sep 25 '17 at 15:55