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

net.uncontended.precipice.factories.Asynchronous Maven / Gradle / Ivy

There is a newer version: 0.7.0
Show newest version
/*
 * Copyright 2016 Timothy Brooks
 *
 * 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.
 *
 */

package net.uncontended.precipice.factories;

import net.uncontended.precipice.Failable;
import net.uncontended.precipice.GuardRail;
import net.uncontended.precipice.rejected.RejectedException;
import net.uncontended.precipice.Completable;
import net.uncontended.precipice.concurrent.Eventual;

public class Asynchronous {

    private Asynchronous() {}

    public static  & Failable, Rejected extends Enum, R> Eventual
    acquireSinglePermitAndPromise(GuardRail guardRail) {
        return acquirePermitsAndPromise(guardRail, 1L, null);
    }

    public static  & Failable, Rejected extends Enum, R> Eventual
    acquireSinglePermitAndPromise(GuardRail guardRail, Completable externalCompletable) {
        return acquirePermitsAndPromise(guardRail, 1L, externalCompletable);
    }

    public static  & Failable, Rejected extends Enum, R> Eventual
    acquirePermitsAndPromise(GuardRail guardRail, long number) {
        return acquirePermitsAndPromise(guardRail, number, null);
    }

    public static  & Failable, Rejected extends Enum, R> Eventual
    acquirePermitsAndPromise(GuardRail guardRail, long number, Completable externalCompletable) {
        long startTime = guardRail.getClock().nanoTime();
        Rejected rejected = guardRail.acquirePermits(number, startTime);
        if (rejected != null) {
            throw new RejectedException(rejected);
        }
        return getPromise(guardRail, number, startTime, externalCompletable);
    }

    public static  & Failable, Rejected extends Enum, R> Eventual
    getPromise(GuardRail guardRail, long permitNumber, long nanoTime) {
        return getPromise(guardRail, permitNumber, nanoTime, null);
    }

    public static  & Failable, Rejected extends Enum, R> Eventual
    getPromise(GuardRail guardRail, long permitNumber, long nanoTime, Completable externalCompletable) {
        Eventual promise = new Eventual<>(permitNumber, nanoTime, externalCompletable);
        promise.internalOnComplete(guardRail.releaseFunction());
        return promise;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy