IamVeryClever
IamVeryClever

Reputation: 35

About thread safe

In https://github.com/Readify/Neo4jClient/wiki/connecting#threading-and-lifestyles, it mentioned that You should only have one instance of it for each database. Can I create more than one instance if I want to using multi-threads? For example, I want to do following things:

main() {
    for ( int i = 0 ; i < 10 ; ++i )
        ( new System.Threading.Thread( newUser() ) ).Start() ;
}
void newUser() {
    var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
    client.Connect();
    /* do sth... */
}

For the reason that I want to simulate multi-user scenario. I tried this code and it seems like works well. Why is it said I can have only one instance for my DB in document?

Upvotes: 1

Views: 68

Answers (1)

Charlotte Skardon
Charlotte Skardon

Reputation: 6280

You can do what you want! It's only a recommendation, in a typical scenario you would have only one instance and use it to save on extra calls to Connect etc.

The main thing we're trying to prevent is where someone has a method like this:

private static Element Get() {
    var client = new GraphClient(...);
    client.Connect();

    var q = client.Cypher.DOQUERYHERE
    return q.Results.Single();
}

Where everytime they call Get they create a new instance, the overhead of doing so would make the code very inefficient.

So, the long and short is - if you want to have multiple instances - of course you can, the scenario you have is a good reason.

Upvotes: 1

Related Questions