2

Should I use a ReadWriteLock on the functions of the contentprovider?

In the query of the contentprovider I do getReadableDatabase, then check if its open and do the query. But sometimes it crashes on DatabaseIsClosed exeption. This could be that an other process does an insert that does a getWritebleDatabase which closes the first one.

I am using an app and a service who query and insert on the contentprovider constantly. So it seems that the contentprovider isn't threadsafe.

Could it help to make the function synchronized?

Thanks!

Ion Aalbers
  • 7,830
  • 3
  • 37
  • 50

1 Answers1

1

In the query of the contentprovider I do getReadableDatabase, then check if its open and do the query. But sometimes it crashes on DatabaseIsClosed exeption. This could be that an other process does an insert that does a getWritebleDatabase which closes the first one.

You should be keeping your database open for the lifetime of the ContentProvider, AFAIK.

So it seems that the contentprovider isn't threadsafe.

AFAIK, a ContentProvider is only ever called on one thread.

ContentProvider is mostly a facade and does not provide any intrinsic thread safety.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Inside the [AlarmProvider](http://www.grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.2.1_r1/com/android/alarmclock/AlarmProvider.java#AlarmProvider) they also get a new readable/writeable database on every insert/query/update. Like I do. But They don't close the received database, whys that? This should be unstable as well, but I guess that we query and insert more often then the AlarmProvider. – Ion Aalbers Sep 06 '11 at 12:42
  • @CommonsWare you might want to update your answer... `ContentProvider` can be called from many threads at once, as per the [documentation](http://developer.android.com/reference/android/content/ContentProvider.html). To be fair, I don't think this was very clear way back last September. :) – Alex Lockwood Oct 12 '12 at 02:28
  • @AlexLockwood: Yeah, one of the early arguments for why one would want to use a `ContentProvider` was the thread safety it supplied... which isn't the case. Thanks for pointing out the flawed answer! – CommonsWare Oct 12 '12 at 11:06