Search code examples
androiddatabasesingletonblocking

Keeping Single Database Connection on Android


This question seems very similar to many I have read but then again, I did not find any code that would satisfy me. (or I am too sleepy to realize that)

I have a singleton database helper to ensure only one of them exists. The problem is not here. I encounter a problem when trying to ensure only one database connection exists while still using getReadableDatabase and getWritableDatabse methods.

I know it returns the same reference in most cases and I can handle use of it but I don't know what to do in case I have read-only connection open (probably was running out of memory) and another thread wants to open a writable connection. I would like to block the writing thread until read-only connection is closed and then attempt to open a writable connection.

How do you do that? That, probably, can be done in Java only with some thread locking but not sure which methods should be used.

P.S. In case I am missing something - feel free to show me how it should be done in another way.


Solution

  • I've gone through the same issues in the past and synchronization is the answer. Simply put, synchronize on the databasehelper instance.Or what you can do is create a wrapper method for getWritableDatabase and use the synchronized keyword in the method declatation. Then never call getReadableDatabase but just the wrapper method. Since getReadableDB and getWritableDB give the same reference, it's safe to do so. Make sense?