5

I am developing an app which uses Couchbase to sync the documents. Right now all the documents I am creating on main thread and using the same.

But now I got stuck in a scenario where I need to create and push the document in some other thread than main, not blocking the UI.

How I can run the part of Couchbase database in background thread to support only above scenario.

Tried the methods in the Couchbase documentation for concurrency support.But receiving the thread safety crash crash telling whenever I create documents in the background thread like this.

DispatchQueue.global(qos: .background).async {
   //creating couchbase documents here
}

Getting below crash:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '***** THREAD-SAFETY VIOLATION: This database is being used on a thread it wasn't created on! Please see the concurrency guidelines in the Couchbase Lite documentation. *****

Please help.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
Shyam
  • 417
  • 4
  • 16

1 Answers1

4

Couchbase Lite APIs in 1.x are not thread safe and support a thread confinement model. So you cannot share objects across threads - In other words, if you created a CBLDatabase object on main thread, you cannot use that instance on your background thread. You will have to create a new instance for your background thread. So do the following :

  • Create a new serial dispatch queue
  • Create a CBLManager instance
  • Set the manager’s dispatchQueue property to the queue you created
  • Do your Couchbase Lite calls inside dispatch_async calls on your queue.

As an aside, Couchbase Mobile 2.0 APIs are thread safe and something you may want to consider if this is a greenfield project.

rajagp
  • 1,443
  • 8
  • 10
  • Can I use global background queues here or do I need to create only serial queue? – Shyam Mar 28 '18 at 10:03
  • Chceked.Still I am getting same crash.Do I need to create separate CBLDatabase instance to run the tasks in background thread? – Shyam Mar 28 '18 at 10:21
  • Now I am getting below crash. *** Assertion failure in -[CBL_FMDatabase beginUse], /Users/jenkins/jenkins/workspace/couchbase-lite-ios-builds/couchbase-lite-ios-community/vendor/fmdb/src/FMDatabase.m:979 – Shyam Mar 29 '18 at 06:38
  • For concurrent queues you need to create a database object each time since there is no thread safety in those. Don't forget to close it when you are done. – borrrden Apr 03 '18 at 05:35
  • @borrrden i am working on cblite 2.1.0 and i am facing same issue, database.addchangelistener continusly upating one of the screen irrespective whether i am on that screen or not , so it blocking my ios app ui , could you help me on thi – Shobhakar Tiwari Dec 30 '18 at 18:45