If a second thread reads that there is no node with external_id 123 in
between the time that a first thread finds no node and elects to create it,
you will get 2 nodes with external_id 123. So yes, you need to introduce a
lock and synchronize.

You can create read locks in the graph database but you probably will not
need to do that. In your case you are reading from an index and I am not
sure what locks are available for indexes. If you are running an embedded
database and you can be sure that only your one JVM will access the database
then you can just lock in the Java thread/object space and elect that other
threads must wait to read if the node exists until the first thread has
created it. If you need to communicate concurrency via the database, you
will have to do all the same locking in the Java space and add a read lock
on some control node in Neo4j.

If you want to create a read lock on a node you can do the following:

lockManager = graphDb.getConfig().getLockManager();
lockManager.getReadLock(someNode);
...
lockManager.releaseReadLock(someNode, null);

Threading and synchronization in Java will perform great. Depending on your
model, most of the time your node will exist and two or more threads will
just queue up and get the same reference. That waiting is inefficient by
nature, but if your business rules require it then you have to do it.

Cheers,

McKinley

On Wed, Sep 14, 2011 at 12:45 PM, Linan Wang <tali.w...@gmail.com> wrote:

> hi all,
> I have implemented a function
> UserFactory.get_or_create_with_external_id(long external_id). the
> function basically search the index, see if a node already created and
> has the property "external_id" equals to external_id. if there is such
> a node, return, if not, create one, assign property and index it.
> this function will be called inside of transactions, from unmanaged
> extensions. so it's multi-threaded scenario.
> my question is if i need to mark the function synchronized. my guess
> is true, and i feel it'll hurt performance badly. if my guess is
> wrong, why? thanks
>
> --
> Best regards
>
> Linan Wang
> _______________________________________________
> Neo4j mailing list
> User@lists.neo4j.org
> https://lists.neo4j.org/mailman/listinfo/user
>
_______________________________________________
Neo4j mailing list
User@lists.neo4j.org
https://lists.neo4j.org/mailman/listinfo/user

Reply via email to