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.9.8
Show newest version
/**
 * Copyright 2015-2019 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.AtomicReference;

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

    static class DelegatingCallable implements Callable {

        final private AtomicReference> delegateRef = new AtomicReference<>(null);

        void setup(Callable delegate) {
            boolean updated = delegateRef.compareAndSet(null, delegate);
            if (!updated) {
                throw new IllegalStateException("Delegate may be set only once");
            }
        }

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

    }

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

    @Override
    void fireTransition(Callable code) {
        DelegatingCallable transitionCall = (DelegatingCallable) action;
        transitionCall.setup(code);
        task.run();
    }

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