ARTICLE AD BOX
Suppose you have a REST server. Spring WebFlux, Hibernate, the usual.
You need to make sure all POSTs with the same body property value are processed sequentially. Say, "slotId": no more than one patient can claim a given appointment slot. Such requests should be processed one after another (the second one would gracefully fail).
We already have one such property ("referralId"). Now, we need to synchronize on the aforementioned "slotId" as well. Our current way to synchronize is ugly and lacks flexibility.
DbAppointmentResult src = sync.referralIdSync(referralId, () -> daoApi.setappointment(organizationId, referralId, patientId, slotId, previousSlotId)); import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @Component public class Sync { private ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<>(); public <T> T referralIdSync(String referralId, Supplier<T> sup) { AtomicInteger obj = new AtomicInteger(); AtomicInteger mon = map.putIfAbsent(referralId, obj); if (mon==null) { mon = obj; } mon.incrementAndGet(); try { synchronized(mon){ return sup.get(); } } finally { if (mon.decrementAndGet()==0) { map.remove(referralId); } } } }What is the best way to achieve it? I'm sure it's been covered by Spring.
Java 8.
