feat(commons): utility interface for attaching instances of an object to contexts

This commit is contained in:
Johannes Frohnmeyer 2024-04-13 13:23:04 +02:00
parent 19cf847382
commit 98fae535e7
Signed by: Johannes
GPG Key ID: E76429612C2929F4
1 changed files with 25 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package io.gitlab.jfronny.commons.concurrent;
import io.gitlab.jfronny.commons.throwable.Assume;
public interface WithScopedValue<T> {
ScopedValue<T> getAttached();
T self();
default <TEx1 extends Throwable, TEx2 extends Throwable> void withContext(Action<TEx1, TEx2> action) throws TEx1, TEx2 {
Assume.<TEx1>reintroduce();
Assume.<TEx2>reintroduce(() -> ScopedValue.runWhere(getAttached(), self(), Assume.isSafe(action::run)));
}
default <T, TEx1 extends Throwable, TEx2 extends Throwable> T withContext(Returnable<T, TEx1, TEx2> action) throws TEx1, TEx2 {
Assume.<TEx1>reintroduce();
return Assume.<T, TEx2>reintroduce(() -> ScopedValue.getWhere(getAttached(), self(), Assume.isSafe(action::run)));
}
interface Returnable<T, TEx1 extends Throwable, TEx2 extends Throwable> {
T run() throws TEx1, TEx2;
}
interface Action<TEx1 extends Throwable, TEx2 extends Throwable> {
void run() throws TEx1, TEx2;
}
}