com.slimgears.util.stream.Synchornized Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of stream-utils Show documentation
Show all versions of stream-utils Show documentation
General purpose utils / module: stream-utils
package com.slimgears.util.stream;
import java.util.concurrent.Callable;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class Synchornized {
interface SynchronizedInvoker {
Supplier of(Supplier supplier);
Supplier ofUnsafe(Callable callable);
Runnable ofUnsafe(Safe.UnsafeRunnable runnable);
Runnable of(Runnable runnable);
Function of(Function func);
BiFunction of(BiFunction func);
}
public static T withLock(Object lock, Callable callable) {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (lock) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static SynchronizedInvoker withLock(Object lock) {
return new SynchronizedInvoker() {
@Override
public Supplier of(Supplier supplier) {
return () -> withLock(lock, supplier::get);
}
@Override
public Supplier ofUnsafe(Callable callable) {
return () -> withLock(lock, callable);
}
@Override
public Runnable ofUnsafe(Safe.UnsafeRunnable runnable) {
return () -> withLock(lock, () -> { runnable.run(); return null; });
}
@Override
public Runnable of(Runnable runnable) {
return ofUnsafe(runnable::run);
}
@Override
public Function of(Function func) {
return arg -> withLock(lock, () -> func.apply(arg));
}
@Override
public BiFunction of(BiFunction func) {
return (arg1, arg2) -> withLock(lock, () -> func.apply(arg1, arg2));
}
};
}
}