All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.slimgears.util.stream.Synchornized Maven / Gradle / Ivy

There is a newer version: 0.7.58
Show newest version
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));
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy