Multithread unique model creation

Create multiple models with a common unique key. StoreLocatorFeature: code : unique:true no unique index on DB level In both cases, using the saveAll and save methods, a successful execution resulted in the creation of multiple records.
 avatar
unknown
groovy
2 years ago
1.3 kB
3
Indexable
import java.time.Instant
import java.util.concurrent.*
import de.hybris.platform.core.Registry;
import de.hybris.platform.core.Tenant;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.commerceservices.model.storelocator.StoreLocatorFeatureModel
import de.hybris.platform.servicelayer.model.ModelService

CountDownLatch latch = new CountDownLatch(1);
ModelService modelService = spring.getBean("modelService");
def featureCode = "uniqueCode2"

def func = {aa ->
    println aa + " created, blocked by the latch at " + Instant.now()

    Registry.activateMasterTenant()
    def Tenant tenant = Registry.getCurrentTenantNoFallback();
    try {
        Registry.setCurrentTenant(tenant);
        JaloSession.getCurrentSession().activate();

        def slFeature = modelService.create(StoreLocatorFeatureModel.class);

        latch.await();
        println aa + " starts at " + Instant.now()

        slFeature.setCode(featureCode);
        slFeature.setName(featureCode + Instant.now());
        //modelService.save(slFeature);
        modelService.saveAll(slFeature);

        return slFeature;
    } finally {
        JaloSession.deactivate();
        Registry.unsetCurrentTenant();
    }
}

for (i in 0..5) {
    def idx = i
    Thread.start{func(idx)}
}

sleep(1000)

println "Now release the latch:"
latch.countDown();
Editor is loading...