Loaded objects in different threads

Can we be sure that if we load the same entity (or relationship) in multiple threads, the loaded objects are not the same? (They represent the same entity or relation, but I'm asking about the same java objects).

If you open a fresh Session for every thread and load the same nodes from the graph, the Java objects are independent. But be aware that OGM does its mapping based on the identifiers. So two different Java objects with the same id value will always be seen as the same when it comes to the persistence of those. To avoid conflicts it might be a good advice to look in the optimistic locking section of the documentation.

Thanks.

  1. Does Spring Data Neo4j open a "fresh" session for each thread?
  2. What about each transaction in a single thread?
  3. One more thing: If Neo4j uses caching for objects, doesn't this cause to retrieve the same java object in different threads?
  1. Yes, because the Session is bound to a @Transactional transaction and will throw an exception if accessed from multiple threads.
  2. See 1. :wink:
  3. The caches belong to each Session. You will have duplicated objects in different session caches but accessing them will never return an object from another session but its very own.
1 Like

@gerrit.meier You said: " The caches belong to each Session ." Is the cache you mentioned the same as the page cache? If they are the same, doesn't your sentence mean that, e.g., if many threads try to read the the same node, no cache is used because the threads use different sessions?