Litedb: Question about multi-thread concurrency

Created on 23 Dec 2016  路  4Comments  路  Source: mbdavid/LiteDB

As I understand it, v3 is designed to work efficiently under a multi-threaded process where multiple threads may read and write data concurrently.

Should each process share the same LiteDatabase instance (and/or collections), or should each thread create its own instance of LiteDatabase and LiteCollections?

question

Most helpful comment

Yes, LiteDatabase is thread safe. Take a look on this unit tests (same LiteDatabase instance):

https://github.com/mbdavid/LiteDB/blob/master/LiteDB.Tests/Concurrency/ThreadTest.cs

And this, about be process-safe (multiple LiteDatabase instances)

https://github.com/mbdavid/LiteDB/blob/master/LiteDB.Tests/Concurrency/ProcessTest.cs

All 4 comments

I have plans to write wiki with more details about this. But basicly is:

  • Are you in a shared in-process enviorment? So share your always open LiteDatabase instance. It's is fast because cached pages.

  • If your enviorment are multi-process, use one instance per process.

It's important to undersant that is "expensive" open/close datafile (and journal). This always happend when you create new instance.

Have plans to use Transactions? Use an exclusive instance for that. Transaction are not thread safe.

About LiteCollection doesnt metter, has no difference betten share same/re-create. LiteCollection is just a simple stub (has no state).

So share your always open LiteDatabase instance. It's is fast because cached pages.

So to clarify, I understand that you are saying the following:

  1. LiteDatabase is threadsafe in that multiple threads may call on methods of the same instance.

  2. A single LiteDatabase instance should be shared amongst multiple threads.

Is this correct?

Yes, LiteDatabase is thread safe. Take a look on this unit tests (same LiteDatabase instance):

https://github.com/mbdavid/LiteDB/blob/master/LiteDB.Tests/Concurrency/ThreadTest.cs

And this, about be process-safe (multiple LiteDatabase instances)

https://github.com/mbdavid/LiteDB/blob/master/LiteDB.Tests/Concurrency/ProcessTest.cs

That's great. Thanks for reply.

Was this page helpful?
0 / 5 - 0 ratings