neo4j / neo4j-ogm

Java Object-Graph Mapping Library for Neo4j
https://neo4j.com/docs/ogm-manual/
Apache License 2.0
337 stars 165 forks source link

org.neo4j.ogm.metadata.LazyInstance is not thread safe #456

Closed rkaran4 closed 6 years ago

rkaran4 commented 6 years ago

Expected Behavior

LazyInstance should be thread safe. Calling LazyInstance.get() from multiple theads should create only a single instance in one thread and all threads should receive this instance.

Current Behavior

If multiple threads call get on a LazyInstance object, they may not get already initialized instance due to thread local cache and create a new copy of instance.

Possible Solution

To fix this one can make use of AtomicMarkableReference to update initialized flag and instance in an atomic operation. The following commit contains the required change. https://github.com/rcodekaran/neo4j-ogm/commit/979567f2ab5ba6c2ec041436ea77692accceeb22

Steps to Reproduce (for bugs)

Create around 100 threads and call on a single LazyInstance object and count the number of times a new instance gets created.

frant-hartm commented 6 years ago

Hi,

we are aware it is not thread-safe. It is used in places as a cache to replace multiple expensive calls returning same result to just one (or a few) calls.

The LazyInstance class should not be used from user's code.

So I am closing. If this causes real issue feel free to reopen with a test case.