package io.quarkus.hibernate.orm.runtime;

import java.util.HashMap;
import java.util.Map;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;

import io.quarkus.hibernate.orm.runtime.entitymanager.TransactionScopedEntityManager;

public class TransactionEntityManagers {

    @Inject
    TransactionSynchronizationRegistry tsr;

    @Inject
    TransactionManager tm;

    @Inject
    JPAConfig jpaConfig;

    @Inject
    Instance<RequestScopedEntityManagerHolder> requestScopedEntityManagers;

    private final Map<String, TransactionScopedEntityManager> managers;

    public TransactionEntityManagers() {
        this.managers = new HashMap<>();
    }

    public EntityManager getEntityManager(String unitName) {
        return managers.computeIfAbsent(unitName,
                un -> new TransactionScopedEntityManager(tm, tsr, jpaConfig.getEntityManagerFactory(un), unitName,
                        requestScopedEntityManagers));
    }

}

@@ -53,16 +53,37 @@
 va.util.
+concurrent.Concurrent
 HashMap;
@@ -100,16 +100,37 @@
 va.util.
+concurrent.Concurrent
 Map;%0A%0Aim
@@ -524,18 +524,49 @@
 gistry t
-s
 r
+ansactionSynchronizationRegistry
 ;%0A%0A    @
@@ -596,17 +596,33 @@
 anager t
-m
+ransactionManager
 ;%0A%0A    @
@@ -761,16 +761,26 @@
 e final 
+Concurrent
 Map%3CStri
@@ -895,16 +895,26 @@
 s = new 
+Concurrent
 HashMap%3C
@@ -998,49 +998,149 @@
     
-return managers.computeIfAbsent(unitName,
+TransactionScopedEntityManager entityManager = managers.get(unitName);%0A        if (entityManager != null) %7B%0A            return entityManager;
 %0A   
@@ -1144,24 +1144,26 @@
         
+%7D%0A
         
 un -%3E ne
@@ -1158,56 +1158,164 @@
     
-un -%3E new TransactionScopedEntityManager(tm, tsr
+return managers.computeIfAbsent(unitName, (un) -%3E new TransactionScopedEntityManager(%0A                transactionManager, transactionSynchronizationRegistry
 , jp
@@ -1357,24 +1357,10 @@
 , un
-itName,%0A        
+,%0A
     

Fix thread safety of TransactionEntityManagers