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

com.microsoft.azure.documentdb.internal.query.FetchScheduler Maven / Gradle / Ivy

/*
 * The MIT License (MIT)
 * Copyright (c) 2017 Microsoft Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.microsoft.azure.documentdb.internal.query;

import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FetchScheduler {

    private final Logger logger = LoggerFactory.getLogger(FetchScheduler.class);
    private final Object lock = new Object();
    private final ExecutorCompletionService ex;
    private final LinkedList> waitList;
    private final AtomicInteger concurrencyPermit;
    private final int maxDegreeOfParallelism;
    private boolean stopped = false;

    public FetchScheduler(Executor executor, int maxDegreeOfParallelism) {
        this.maxDegreeOfParallelism = maxDegreeOfParallelism;
        @SuppressWarnings("serial")
        BlockingQueue> completedQueue = new LinkedBlockingQueue>() {
            @Override
            public boolean add(Future e) {
                // adds the completed future to the completed queue
                // and take one task from waitList (if any) and try to invoke it
                // also updates the permits count
                logger.trace("task Completed!");
                synchronized (lock) {
                    concurrencyPermit.incrementAndGet();
                    tryInvokeNext();
                }
                return super.add(e);
            }
        };
        this.ex = new ExecutorCompletionService(executor, completedQueue);

        this.waitList = new LinkedList<>();
        this.concurrencyPermit = new AtomicInteger(maxDegreeOfParallelism);
    }

    private boolean tryInvokeNext() {
        // the caller must hold the lock
        if (waitList.isEmpty() || stopped) {
            return false;
        }
        logger.trace("task invoked");
        // removes the head of wailing list submit it for execution
        // and updates the permit count
        this.ex.submit(waitList.removeFirst());
        concurrencyPermit.decrementAndGet();
        return true;
    }

    public void schedule(Callable callable) {
        logger.trace("scheduling");
        synchronized (lock) {
            if (stopped) {
                logger.debug("already stopped won't schedule!");
                return;
            }

            logger.trace("number of available permits {}", concurrencyPermit.get());
            // adds the task to waiting list
            // and try to invoke a task if there is a permit
            waitList.add(callable);
            if (concurrencyPermit.get() > 0) {
                tryInvokeNext();
            }
        }
    }

    public int getMaxDegreeOfParallelism() {
        return maxDegreeOfParallelism;
    }

    public void stop() {
        // removes only the tasks waiting in the list
        synchronized (lock) {
            waitList.clear();
            stopped = true;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy