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

com.firefly.utils.concurrent.BlockingTask Maven / Gradle / Ivy

There is a newer version: 5.0.2
Show newest version
package com.firefly.utils.concurrent;

import com.firefly.utils.exception.CommonRuntimeException;

import java.util.concurrent.ForkJoinPool;
import java.util.function.Supplier;

/**
 * @author Pengtao Qiu
 */
public class BlockingTask {

    public static  T callInManagedBlock(final Supplier supplier) {
        final SupplierManagedBlock managedBlock = new SupplierManagedBlock<>(supplier);
        try {
            ForkJoinPool.managedBlock(managedBlock);
        } catch (InterruptedException e) {
            throw new CommonRuntimeException(e);
        }
        return managedBlock.getResult();
    }

    private static class SupplierManagedBlock implements ForkJoinPool.ManagedBlocker {
        private final Supplier supplier;
        private T result;
        private boolean done = false;

        private SupplierManagedBlock(final Supplier supplier) {
            this.supplier = supplier;
        }

        @Override
        public boolean block() {
            result = supplier.get();
            done = true;
            return true;
        }

        @Override
        public boolean isReleasable() {
            return done;
        }

        public T getResult() {
            return result;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy