/reactor-lock

Exclusive locking for Mono and CacheMono in the reactive style

Primary LanguageJavaApache License 2.0Apache-2.0

Exclusive locking for Mono and CacheMono in the reactive style

This library provides the way to perform any computations wrapped with Mono with exclusive locking in the reactive manner.

In most cases you should avoid to use it. But if you have the requirement to minimize concurrent calls of some services with or without caching, reactor-lock may be useful.

Usage

Dependencies

Maven

<dependency>
  <groupId>com.github.alex-pumpkin</groupId>
  <artifactId>reactor-lock-core</artifactId>
  <version>0.1.0</version>
</dependency>

Gradle

implementation 'com.github.alex-pumpkin:reactor-lock-core:0.1.0'

Exclusive subscription by key

public <K, V> Mono<V> callServiceByKeyWithLock(K key) {
    return LockMono.key(key)
            .lock(callServiceByKey(key));
}

private <K, V> Mono<V> callServiceByKey(K key) {
    return Mono.fromCallable(() -> {...});
}

Caching with exclusive subscription to the original Mono

Cache doesn’t implement Map interface

public <K, V> Mono<V> callServiceByKeyWithCache(K key) {
    return LockCacheMono.create(LockMono.key(key).build())
            .lookup(k -> Mono.justOrEmpty(CACHE.get(k)).map(Signal::next))
            .onCacheMissResume(() -> callServiceByKey(key))
            .andWriteWith((k, signal) -> Mono.fromRunnable(() -> Optional.ofNullable(signal.get())
                    .ifPresent(v -> CACHE.put(k, v))));
}

private <K, V> Mono<V> callServiceByKey(K key) {
    return Mono.fromCallable(() -> {...});
}

Cache implements Map interface

Map<K, Signal<V>> MAP_CACHE = ...;

public <K, V> Mono<V> callServiceByKeyWithCache(K key) {
    return LockCacheMono.create(LockMono.key(key).build())
            .lookup(MAP_CACHE)
            .onCacheMissResume(() -> callServiceByKey(key));
}

private <K, V> Mono<V> callServiceByKey(K key) {
    return Mono.fromCallable(() -> {...});
}

License

Copyright 2019 Alexander Pankin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.