0

I wanted to persist a list of entities using JPA. My first approach was as follows:

List<myEntity>entityList=myService.getMyEntities();`
\\some other activities...`
entityList.parallelStream().forEach(l->l.setMyStatus(MyStatus.newStatus);
entityList.parallelStream().forEach(l->myService.getEntityManager().merge(l));

But I got an OptimisticLockException.

My second approach was using streams instead of parallel streams.

entityList.stream().forEach(l->myService.getEntityManager().merge(l));

The second approach works! Now my question is why parallelStream() cause optimistic locking exceptions ?

Lakshi
  • 490
  • 4
  • 10

1 Answers1

1

The immediate answer Google produces on "Optimistic Locking", pointing to this question:

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back.

If your list contains the same entry twice, it might be read twice in parallel, then merged once, and when merging the second time the exception is thrown. If you do it without a parallel stream, you read-write-read-write, and hence there are no version conflicts. Basically, you must write back before someone else can read and change again.

Have you checked that the entities in the list are unique?

Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
  • Yes ! I checked. They are unique. Thats why i am wondering. I get those entities from a data table where each one has unique ID. – Lakshi Oct 16 '17 at 19:16
  • Do those entities have shared linked properties? Does the exception indicate anything about where exactly the error occurs? – Malte Hartwig Oct 17 '17 at 09:05
  • Yes . They have relational one -to-one entities but they are unique. No crossed relations – Lakshi Oct 17 '17 at 09:54
  • Hmm, sounds tricky. Hard to continue without knowing the schema and without debugging to find the ones that cause the exceptions. Sorry... – Malte Hartwig Oct 17 '17 at 10:00
  • The thing is that each entitiy can be updeted in parallel. The Question is how parallel stream act on that – Lakshi Oct 17 '17 at 11:18