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

com.englishtown.promises.impl.DefaultScheduler Maven / Gradle / Ivy

There is a newer version: 3.1.1
Show newest version
package com.englishtown.promises.impl;

import com.englishtown.promises.Scheduler;

import javax.inject.Inject;
import javax.inject.Provider;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;

/**
 * Default implementation of {@link com.englishtown.promises.Scheduler}
 */
public class DefaultScheduler implements Scheduler {

    private final Executor _enqueue;
    private final Queue _handlerQueue;
    private final Queue _afterQueue;
    private boolean _running;

    @Inject
    public DefaultScheduler(Provider enqueue) {
        this._enqueue = enqueue.get();
        this._handlerQueue = new ConcurrentLinkedQueue<>();
        this._afterQueue = new ConcurrentLinkedQueue<>();
        this._running = false;
    }

    /**
     * Enqueue a task. If the queue is not currently scheduled to be
     * drained, schedule it.
     *
     * @param task task to be run
     */
    @Override
    public void enqueue(Runnable task) {
        this._handlerQueue.add(task);
        if (!this._running) { // TODO: sync
            this._running = true;
            this._enqueue.execute(this::drain);
        }
    }

    @Override
    public void afterQueue(Runnable task) {
        this._afterQueue.add(task);
        if (!this._running) {
            this._running = true;
            this._enqueue.execute(this::drain);
        }
    }

    /**
     * Drain the handler queue entirely, being careful to allow the
     * queue to be extended while it is being processed, and to continue
     * processing until it is truly empty.
     */
    public void drain() {
        Queue q = this._handlerQueue;
        Runnable task = q.poll();

        while (task != null) {
            task.run();
            task = q.poll();
        }

        this._running = false;

        q = this._afterQueue;
        task = q.poll();
        while (task != null) {
            task.run();
            task = q.poll();
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy