1

I'm wondering if in c# I should create new instance of Google.Cloud.Datastore.V1.DatastoreDb every time I want to use it or I can keep one global instance as a singleton?

This is in c# .net core 3 on linux with Assembly Google.Cloud.Datastore.V1, Version=2.1.0.0

using Google.Cloud.Datastore.V1;

void DoStuff()
{
    var db = DatastoreDb.Create("my-project")
    db.Insert(entity);
}

vs.

using Google.Cloud.Datastore.V1;

static db = DatastoreDb.Create("my-project")

void DoStuff()
{
     db.Insert(entity);
}
theduck
  • 2,589
  • 13
  • 17
  • 23
mbican
  • 98
  • 1
  • 6
  • Is it explicitly documented somewhere as thread-safe? If not, then you should assume that it's not. But you can also walk a middle path - have a pool of instances that are handed out to threads as they need them and later reused. – Vilx- Oct 12 '19 at 12:29

2 Answers2

2

Yes, DatastoreDb doesn't contain any local mutable state, and is thread-safe. We recommend that you use a single instance of it to avoid potentially opening more network connections than are necessary.

DatastoreTransaction, however, does contain local state, and is not thread-safe. (It has no thread affinity, but there's no protection against multiple threads attempting to add mutations at the same time, for example.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

You can use "com.google.cloud.datastore" which is a wrapper that uses v1 library link. "com.google.cloud.datastore" is thread safe acording to this answer link.

marian.vladoi
  • 7,663
  • 1
  • 15
  • 29