reactor-addons icon indicating copy to clipboard operation
reactor-addons copied to clipboard

Suggest reactor version of semaphore implementation

Open semistone opened this issue 2 years ago • 4 comments

Motivation

in non-reactive programming, we could use synchronized or semaphore to guarantee only one thread enters some critical block. e.g: public synchronized fun() { ... }

even though we already use the reactor, we still don't want the same user to call our service before the previous request is finished because some of our libraries aren't thread-safe. but in reactor programming, we don't want to control that in the synchronized block or semaphore as those are blocking methods.

Desired solution

provide a simple utility like

ReactorSemaphore reactorSemaphore = new ReactorSemaphore(1);
Mono<?> mono1 = reactorSemaphore.acquire(lock -> Mono.just("test1")...)
Mono<?> mono2 = reactorSemaphore.acquire(lock -> Mono.just("test2")...)

when mono1 and mono2 subscribe at the same time, they will subscribe first mono and only after the first mono is terminated, then subscribe second one. which is similar to controlled by Semaphore. but implemented in a non-blocking way.

actually, I already implement that utility, but still wondering do you have any suggestions or a better way to solve this problem by native reactor library. or if you are interested, I could share my utility later.

Considered alternatives

Additional context

semistone avatar Mar 23 '23 05:03 semistone

@semistone transferred to addons

OlegDokuka avatar Mar 23 '23 13:03 OlegDokuka

https://github.com/semistone/reactorSemaphore/blob/main/src/main/java/ReactorSemaphore.java

semistone avatar Mar 24 '23 01:03 semistone

I had done a few unit tests, it's simple POC but it worked.

semistone avatar Mar 24 '23 01:03 semistone

Google find something similar https://www.javadoc.io/doc/org.redisson/redisson/3.9.1/org/redisson/api/RSemaphoreReactive.html#tryAcquire(int)

semistone avatar Mar 24 '23 14:03 semistone