how to avoid deadlocks with neo4j

2020-07-18 02:59发布

问题:

I just learnt that when I create a relationship between 2 nodes in neo4j, both of them are locked (http://docs.neo4j.org/chunked/stable/transactions-locking.html). However, in our project, we have elements that we can instanciate and we finnaly have two nodes in the graph linked by a "INSTANCE_OF" relationship. For exemple if I instanciate element B, I have a new element B1. They are stored in the graph like B<-INSTANCE_OF-B1. My problem is that many users can instanciate element B on same time and it result in deadlocks. How can I avoid these deadlocks please ? I don't need to write properties on B, I just want to "attach" B1 to B in my graph. Is having a property in B1 reprensenting the B id would be a better solution instead of linking them with a relationship ? I think it wouldn't since we lost all the graph interest, but I really don't know how to avoid theses deadlocks ?

Thank you very much for your help

回答1:

You have two strategies:

the first, a pessimistic one, is using the LockManager getWriteLock method to acquire an exclusive lock on the node B before adding the related B1 node and unlock it as soon as the relationship creation finishes;

the second, an optimistic one, is to implement a retry strategy in case of deadlock, you can catch the DeadlockDetectedException exception and retry the operation until it's successful.