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

io.convergence_platform.common.tasks.TaskExecutionEngineThread Maven / Gradle / Ivy

Go to download

Holds the common functionality needed by all Convergence Platform-based services written in Java.

The newest version!
package io.convergence_platform.common.tasks;

import java.util.List;
import java.util.Set;

public class TaskExecutionEngineThread {
    private List executionOrder;
    private final Set finishedTasks;
    private final Set failedTasks;
    private volatile boolean finished = false;
    private volatile boolean threadTerminated = false;

    public TaskExecutionEngineThread(List executionOrder, Set finishedTasks, Set failedTasks) {
        this.executionOrder = executionOrder;
        this.finishedTasks = finishedTasks;
        this.failedTasks = failedTasks;
    }

    public void start() {
        new Thread(this::threadMain).start();
    }

    private void threadMain() {
        while (!finished) {
            SubTask taskToRun = getNextTaskToRun();
            if (taskToRun != null) {
                if (taskToRun.execute()) {
                    synchronized (executionOrder) {
                        finishedTasks.add(taskToRun);
                    }
                } else {
                    synchronized (executionOrder) {
                        failedTasks.add(taskToRun);
                    }
                }
            } else {
                waitFor(500);
            }
        }

        threadTerminated = true;
    }

    public boolean isThreadTerminated() {
        return threadTerminated;
    }

    private SubTask getNextTaskToRun() {
        SubTask next = null;

        synchronized (executionOrder) {
            if (executionOrder.size() == 0) {
                return null;
            }

            for (SubTask sub : executionOrder) {
                List dependencies = sub.getDependencies();

                boolean allDependenciesSatisfied = true;
                for (SubTask dep : dependencies) {
                    if (!finishedTasks.contains(dep)) {
                        allDependenciesSatisfied = false;
                        break;
                    }
                }

                if (allDependenciesSatisfied) {
                    executionOrder.remove(sub);
                    next = sub;
                    break;
                }
            }
        }

        return next;
    }

    private void waitFor(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
        }
    }

    public void markFinished() {
        this.finished = true;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy