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

net.tascalate.concurrent.CompletableSubTask Maven / Gradle / Ivy

Go to download

Implementation of blocking (IO-Bound) cancellable java.util.concurrent.CompletionStage and related extensions to java.util.concurrent.ExecutorService-s

There is a newer version: 0.7.1
Show newest version
/**
 * Copyright 2015-2017 Valery Silaev (http://vsilaev.com)
 *
 * 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.tascalate.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * The {@link Promise} implementation for intermediate long-running blocking task
 * @author vsilaev
 *
 * @param 
 */
class CompletableSubTask extends AbstractCompletableTask {

    static class DelegatingCallable implements Callable {

        final private AtomicBoolean setupGuard = new AtomicBoolean(false);
        private Callable delegate;

        void setup(Callable delegate) {
            if (setupGuard.compareAndSet(false, true)) {
                this.delegate = delegate;
            } else {
                throw new IllegalStateException("Delegate may be set only once");
            }
        }

        @Override
        public T call() throws Exception {
            if (!setupGuard.get()) {
                throw new IllegalStateException("Call is not configured");
            } else {
                return delegate.call();
            }
        }

    }

    CompletableSubTask(Executor executor) {
        super(executor, new DelegatingCallable());
    }

    @Override
    Runnable setupTransition(Callable code) {
        DelegatingCallable transitionCall = (DelegatingCallable) action;
        transitionCall.setup(code);
        return task;
    }

    @Override
    protected  AbstractCompletableTask createCompletionStage(Executor executor) {
        return new CompletableSubTask(executor);
    }
}