Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.atomic.AtomicBoolean;
- public interface Task {
- void execute() throws Exception; // Simulate task execution, may throw an exception
- }
- public class TaskScheduler {
- private final Queue<Task> taskQueue = new LinkedList<>();
- private final AtomicBoolean isFailed = new AtomicBoolean(false);
- private final Object lock = new Object(); // Synchronization lock
- private final TaskAPI taskAPI; // Simulates the external API to fetch dependent tasks
- public TaskScheduler(TaskAPI taskAPI) {
- this.taskAPI = taskAPI;
- }
- // Method to start the scheduler with initial tasks
- public void start(List<Task> initialTasks) {
- synchronized (lock) {
- taskQueue.addAll(initialTasks);
- lock.notify(); // Wake up the main thread if waiting
- }
- Thread mainThread = new Thread(this::mainScheduler);
- mainThread.start();
- }
- // Main scheduler thread
- private void mainScheduler() {
- while (true) {
- Task task;
- // Fetch the next task, wait if the queue is empty
- synchronized (lock) {
- while (taskQueue.isEmpty() && !isFailed.get()) {
- try {
- lock.wait(); // Wait for new tasks
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- }
- if (isFailed.get() || taskQueue.isEmpty()) {
- return; // Exit if there's a failure or no tasks
- }
- task = taskQueue.poll(); // Dequeue the task
- }
- // Schedule the task
- Thread workerThread = new Thread(() -> {
- try {
- task.execute(); // Execute the task
- // Fetch dependent tasks after completion
- List<Task> dependentTasks = taskAPI.getDependentTasks(task);
- // Add new tasks to the queue
- synchronized (lock) {
- taskQueue.addAll(dependentTasks);
- lock.notify(); // Notify the main thread
- }
- } catch (Exception e) {
- isFailed.set(true); // Mark failure
- synchronized (lock) {
- lock.notify(); // Wake up the main thread to exit
- }
- }
- });
- workerThread.start();
- }
- }
- }
- public class TaskAPI {
- public List<Task> getDependentTasks(Task task) {
- // Simulate fetching dependent tasks from the API
- // In reality, this would query a database or external service
- return new ArrayList<>(); // Return an empty list for simplicity
- }
- }
- public class Main {
- public static void main(String[] args) {
- TaskAPI taskAPI = new TaskAPI();
- Task task1 = () -> {
- System.out.println("Executing Task 1");
- Thread.sleep(1000); // Simulate work
- };
- Task task2 = () -> {
- System.out.println("Executing Task 2");
- Thread.sleep(1000);
- };
- Task task3 = () -> {
- System.out.println("Executing Task 3");
- Thread.sleep(1000);
- };
- TaskScheduler scheduler = new TaskScheduler(taskAPI);
- scheduler.start(List.of(task1, task2, task3));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement