diff --git a/pom.xml b/pom.xml index 17cca3d15482..36e89b2f2d26 100644 --- a/pom.xml +++ b/pom.xml @@ -213,6 +213,7 @@ role-object rule-engine saga + scheduler separated-interface serialized-entity serialized-lob diff --git a/scheduler/README.md b/scheduler/README.md new file mode 100644 index 000000000000..a967754dfc19 --- /dev/null +++ b/scheduler/README.md @@ -0,0 +1,266 @@ +--- +title: "Scheduler Pattern in Java: Deciding When and in Which Order Tasks Run" +shortTitle: Scheduler +description: "Learn the Scheduler pattern in Java: separate the work (tasks), the moment it becomes ready (triggers) and the order it runs in (scheduling strategies). Includes FCFS, priority, round robin and shortest-remaining-time-first schedulers with time, interval and condition triggers." +category: Behavioral +language: en +tag: + - Decoupling + - Extensibility + - Performance + - Resource management +--- + +## Also known as + +* Job Scheduler +* Task Scheduler + +## Intent of Scheduler Design Pattern + +Manage the execution of tasks that compete for a limited resource. The pattern keeps three concerns apart: the task that holds the work, the trigger that decides when a task becomes ready, and the scheduler that decides which ready task runs next and for how long. + +## Detailed Explanation of Scheduler Pattern with Real-World Examples + +Real-world example + +> A restaurant kitchen has one chef and many orders. Orders arrive when guests sit down (a fixed time), the bread is baked every morning (an interval), and the dessert is plated only once the main course has left the kitchen (a condition). The head chef does not cook any of them; they decide which order the cook works on next, whether that is the oldest order, the VIP table, a few minutes on each dish in turn, or the dish that is nearly done. + +In plain words + +> The Scheduler pattern decides which piece of work runs next, so the work itself does not have to know about timing or about the other work waiting for the same resource. + +Wikipedia says + +> In computing, scheduling is the action of assigning resources to perform tasks. The resources may be processors, network links or expansion cards. The tasks may be threads, processes or data flows. The scheduling activity is carried out by a mechanism called a scheduler. + +Flowchart + +```mermaid +flowchart TD + A[Clock tick] --> B{Any trigger fires?} + B -- yes --> C[Create task from job and hand it to the scheduler] + C --> D + B -- no --> D[Scheduler picks the next task by its strategy] + D --> E[Run the task for one time slice] + E --> F{Task complete?} + F -- yes --> G[Record completion time] + F -- no --> H[Keep the task queued] + G --> A + H --> A +``` + +![Scheduler class diagram](./etc/scheduler.urm.png) + +## Programmatic Example of Scheduler Pattern in Java + +The example models a single worker that runs tasks in time slices, the way an operating system shares one CPU between processes. It has four parts, matching the elements of the pattern. + +**Task.** A `Task` is the unit of work. The scheduler only needs to know its id, its priority, how much time it still needs and whether it is done. + +```java +public interface Task { + int getId(); + int getPriority(); + int getRemainingTime(); + boolean isComplete(); + void execute(int deltaTime); +} +``` + +`AbstractTask` keeps the time accounting, so a concrete task only implements the work done in one slice. `SimpleTask` only reports its progress, while `SumTask` computes `1 + 2 + ... + n` one number per time unit, so its work can be paused and resumed between slices. + +```java +public abstract class AbstractTask implements Task { + // id, totalExecutionTime, priority and elapsedTime fields + + @Override + public void execute(int deltaTime) { + if (isComplete()) { + throw new IllegalStateException("Task " + id + " is already complete"); + } + var units = Math.min(deltaTime, getRemainingTime()); + doWork(units); + elapsedTime += units; + } + + protected abstract void doWork(int units); +} + +public class SumTask extends AbstractTask { + @Getter private long sum; + private int next = 1; + + @Override + protected void doWork(int units) { + for (var i = 0; i < units; i++) { + sum += next++; + } + } +} +``` + +**Trigger.** A `Trigger` decides when a job hands a new task to the scheduler. `TimeTrigger` fires once at a fixed time, `IntervalTrigger` fires repeatedly like a cron job, and `ConditionTrigger` fires once, the first time a condition becomes true. + +```java +public interface Trigger { + boolean fires(int time); +} + +public record IntervalTrigger(int start, int period) implements Trigger { + @Override + public boolean fires(int time) { + return time >= start && (time - start) % period == 0; + } +} +``` + +A `ScheduledJob` pairs a trigger with a task factory. The factory is needed because a repeating trigger must create a fresh task each time it fires. + +```java +public record ScheduledJob(Trigger trigger, Supplier taskFactory) { + public static ScheduledJob at(int time, Task task) { + return new ScheduledJob(new TimeTrigger(time), () -> task); + } +} +``` + +**Scheduler.** `TaskScheduler` is the strategy that decides which ready task runs next. + +```java +public interface TaskScheduler { + void scheduleTask(Task task); + void update(int deltaTime); +} +``` + +There are four implementations: + +* `FirstComeFirstServedScheduler` runs each task to completion in arrival order. +* `PriorityScheduler` always runs the task with the highest priority, so an arriving high-priority task preempts the running one. +* `RoundRobinScheduler` gives every task one time slice in turn. +* `ShortestRemainingTimeFirstScheduler` runs the task closest to completion. + +```java +public class RoundRobinScheduler implements TaskScheduler { + private final Queue taskQueue = new ArrayDeque<>(); + + @Override + public void scheduleTask(Task task) { + taskQueue.add(task); + } + + @Override + public void update(int deltaTime) { + var task = taskQueue.poll(); + if (task == null) { + return; + } + task.execute(deltaTime); + if (!task.isComplete()) { + taskQueue.add(task); + } + } +} +``` + +**Execution context.** The `Simulator` advances a clock, fires the triggers, hands new tasks to the scheduler, lets the scheduler run one slice and records when each task completes. + +```java +public Map simulate() { + Map completedAt = new LinkedHashMap<>(); + List running = new ArrayList<>(); + for (var time = 0; time < simulateTime; time += deltaTime) { + for (var job : jobs) { + if (job.trigger().fires(time)) { + var task = job.taskFactory().get(); + running.add(task); + scheduler.scheduleTask(task); + } + } + scheduler.update(deltaTime); + // record and drop the tasks that completed in this slice + } + return completedAt; +} +``` + +`App` runs one workload through every scheduler. The workload uses all three trigger types: a backup (task 1) and a sum (task 2) arrive at fixed times, a report (tasks 101 and up) repeats every 10 time units, and a cleanup (task 3) starts only once the backup is complete. + +```java +static List workload() { + var backup = new SimpleTask(1, 5, 1); + var reportIds = new AtomicInteger(100); + return List.of( + ScheduledJob.at(0, backup), + ScheduledJob.at(1, new SumTask(2, 4, 3)), + new ScheduledJob( + new IntervalTrigger(2, 10), () -> new SimpleTask(reportIds.incrementAndGet(), 2, 2)), + new ScheduledJob(new ConditionTrigger(backup::isComplete), () -> new SimpleTask(3, 3))); +} + +public static void main(String[] args) { + List schedulers = + List.of( + new FirstComeFirstServedScheduler(), + new PriorityScheduler(), + new RoundRobinScheduler(), + new ShortestRemainingTimeFirstScheduler()); + for (var scheduler : schedulers) { + var completedAt = new Simulator(scheduler, workload(), 1, 30).simulate(); + LOGGER.info("{} completed tasks at: {}", scheduler.getClass().getSimpleName(), completedAt); + } +} +``` + +The same tasks finish in a different order under each strategy. Each entry maps a task id to the time it completed: + +``` +FirstComeFirstServedScheduler completed tasks at: {1=5, 2=9, 101=11, 3=14, 102=16, 103=24} +PriorityScheduler completed tasks at: {2=5, 101=7, 1=11, 102=14, 3=16, 103=24} +RoundRobinScheduler completed tasks at: {101=8, 1=10, 2=11, 3=15, 102=16, 103=24} +ShortestRemainingTimeFirstScheduler completed tasks at: {101=4, 1=7, 3=10, 2=14, 102=16, 103=24} +``` + +## When to Use the Scheduler Pattern in Java + +* Many tasks compete for a limited resource, such as a thread, a CPU, a connection or a device, and the order in which they run matters. +* Work must start at a given time, repeat on an interval, or wait for an event or for other work to finish. +* The scheduling policy should be changeable without touching the tasks, for example to favour throughput, fairness, latency or business priority. + +## Real-World Applications of Scheduler Pattern in Java + +* `java.util.concurrent.ScheduledExecutorService` runs tasks after a delay or at a fixed rate. +* [Quartz Scheduler](https://www.quartz-scheduler.org/) separates `Job`, `Trigger` and `Scheduler` in the same way as this example. +* Spring's `@Scheduled` and `TaskScheduler` run methods on cron expressions, fixed rates or fixed delays. +* `ForkJoinPool` and the virtual-thread scheduler of the JVM decide which runnable task gets a carrier thread next. +* Operating system process schedulers use the FCFS, priority, round robin and shortest-remaining-time-first policies shown here. + +## Benefits and Trade-offs of Scheduler Pattern + +Benefits: + +* Tasks, triggers and scheduling policies vary independently, so a new policy or a new kind of task needs no change elsewhere. +* Centralises the decision about which work runs, which makes resource usage predictable and easy to tune. +* Supports time-based, periodic and event-driven work through one mechanism. + +Trade-offs: + +* Every policy favours something: FCFS lets a long task block short ones, priority scheduling can starve low-priority tasks, round robin adds switching overhead and SRTF needs to know how long a task will take. +* Preemption requires tasks that can stop and resume safely between time slices. +* The scheduler is a central component; if it is slow or fails, all scheduled work is affected. + +## Related Java Design Patterns + +* [Strategy](../strategy): each scheduling policy is a strategy behind the `TaskScheduler` interface. +* [Command](../command): a task encapsulates a request so that it can be queued and run later. +* [Thread Pool Executor](../thread-pool-executor): a pool of worker threads is the resource a scheduler often hands tasks to. +* [Producer-Consumer](../producer-consumer): triggers produce tasks and the scheduler consumes them. +* [Game Loop](../game-loop): advances a clock and updates the world each tick, much like the simulator here. + +## References and Credits + +* [Scheduling (computing) (Wikipedia)](https://en.wikipedia.org/wiki/Scheduling_(computing)) +* [Operating Systems: Three Easy Pieces, chapters on scheduling (Remzi and Andrea Arpaci-Dusseau)](https://pages.cs.wisc.edu/~remzi/OSTEP/) +* [Quartz Scheduler documentation](https://www.quartz-scheduler.org/documentation/) +* [ScheduledExecutorService (Java SE 21 API)](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/ScheduledExecutorService.html) diff --git a/scheduler/etc/scheduler.urm.png b/scheduler/etc/scheduler.urm.png new file mode 100644 index 000000000000..8ee1c2bd582a Binary files /dev/null and b/scheduler/etc/scheduler.urm.png differ diff --git a/scheduler/etc/scheduler.urm.puml b/scheduler/etc/scheduler.urm.puml new file mode 100644 index 000000000000..f93ef3fef72b --- /dev/null +++ b/scheduler/etc/scheduler.urm.puml @@ -0,0 +1,81 @@ +@startuml +package com.iluwatar.scheduler { + interface Task { + + getId() : int {abstract} + + getPriority() : int {abstract} + + getRemainingTime() : int {abstract} + + isComplete() : boolean {abstract} + + execute(deltaTime : int) {abstract} + } + abstract class AbstractTask { + - id : int + - totalExecutionTime : int + - priority : int + - elapsedTime : int + # AbstractTask(id : int, totalExecutionTime : int, priority : int) + + execute(deltaTime : int) + # doWork(units : int) {abstract} + } + class SimpleTask { + + SimpleTask(id : int, totalExecutionTime : int, priority : int) + # doWork(units : int) + } + class SumTask { + - sum : long + + SumTask(id : int, n : int, priority : int) + + getSum() : long + # doWork(units : int) + } + interface Trigger { + + fires(time : int) : boolean {abstract} + } + class TimeTrigger { + + TimeTrigger(time : int) + } + class IntervalTrigger { + + IntervalTrigger(start : int, period : int) + } + class ConditionTrigger { + - condition : BooleanSupplier + - fired : boolean + + ConditionTrigger(condition : BooleanSupplier) + } + class ScheduledJob { + + ScheduledJob(trigger : Trigger, taskFactory : Supplier) + + at(time : int, task : Task) : ScheduledJob {static} + } + interface TaskScheduler { + + scheduleTask(task : Task) {abstract} + + update(deltaTime : int) {abstract} + } + class FirstComeFirstServedScheduler + class PriorityScheduler + class RoundRobinScheduler + class ShortestRemainingTimeFirstScheduler + class Simulator { + - deltaTime : int + - simulateTime : int + + Simulator(scheduler : TaskScheduler, jobs : List, deltaTime : int, simulateTime : int) + + simulate() : Map + } + class App { + + main(args : String[]) {static} + } +} +AbstractTask ..|> Task +SimpleTask --|> AbstractTask +SumTask --|> AbstractTask +TimeTrigger ..|> Trigger +IntervalTrigger ..|> Trigger +ConditionTrigger ..|> Trigger +FirstComeFirstServedScheduler ..|> TaskScheduler +PriorityScheduler ..|> TaskScheduler +RoundRobinScheduler ..|> TaskScheduler +ShortestRemainingTimeFirstScheduler ..|> TaskScheduler +ScheduledJob --> "-trigger" Trigger +ScheduledJob ..> Task : creates +TaskScheduler ..> Task : runs +Simulator --> "-scheduler" TaskScheduler +Simulator --> "-jobs" ScheduledJob +App ..> Simulator +@enduml diff --git a/scheduler/pom.xml b/scheduler/pom.xml new file mode 100644 index 000000000000..e9df4bc819dc --- /dev/null +++ b/scheduler/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + scheduler + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.scheduler.App + + + + + + + + + diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/AbstractTask.java b/scheduler/src/main/java/com/iluwatar/scheduler/AbstractTask.java new file mode 100644 index 000000000000..dd02e6a7d372 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/AbstractTask.java @@ -0,0 +1,71 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import lombok.Getter; + +/** + * Base class that keeps the time accounting shared by every task. Subclasses only implement {@link + * #doWork(int)}, the actual work done in one time slice. + */ +@Getter +public abstract class AbstractTask implements Task { + private final int id; + private final int totalExecutionTime; + private final int priority; + private int elapsedTime; + + protected AbstractTask(int id, int totalExecutionTime, int priority) { + if (totalExecutionTime <= 0) { + throw new IllegalArgumentException("Total execution time must be positive"); + } + this.id = id; + this.totalExecutionTime = totalExecutionTime; + this.priority = priority; + } + + @Override + public int getRemainingTime() { + return totalExecutionTime - elapsedTime; + } + + @Override + public boolean isComplete() { + return elapsedTime >= totalExecutionTime; + } + + @Override + public void execute(int deltaTime) { + if (isComplete()) { + throw new IllegalStateException("Task " + id + " is already complete"); + } + var units = Math.min(deltaTime, getRemainingTime()); + doWork(units); + elapsedTime += units; + } + + /** Perform the task's own work for the given number of time units. */ + protected abstract void doWork(int units); +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/App.java b/scheduler/src/main/java/com/iluwatar/scheduler/App.java new file mode 100644 index 000000000000..4574f921b178 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/App.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; + +/** + * The Scheduler pattern separates what work is done ({@link Task}), when it becomes ready ({@link + * Trigger}) and in which order it runs ({@link TaskScheduler}). The {@link Simulator} is the + * execution context that ties them together. + * + *

This example runs the same workload through every scheduling strategy. The workload uses all + * three trigger types: tasks arriving at fixed times, a report repeating on an interval, and a + * cleanup task that starts only after a backup completes. + */ +@Slf4j +public class App { + + /** Program entry point. */ + public static void main(String[] args) { + List schedulers = + List.of( + new FirstComeFirstServedScheduler(), + new PriorityScheduler(), + new RoundRobinScheduler(), + new ShortestRemainingTimeFirstScheduler()); + for (var scheduler : schedulers) { + var completedAt = new Simulator(scheduler, workload(), 1, 30).simulate(); + LOGGER.info("{} completed tasks at: {}", scheduler.getClass().getSimpleName(), completedAt); + } + } + + /** Build a fresh workload, since tasks keep their progress once run. */ + static List workload() { + var backup = new SimpleTask(1, 5, 1); + var reportIds = new AtomicInteger(100); + return List.of( + ScheduledJob.at(0, backup), + ScheduledJob.at(1, new SumTask(2, 4, 3)), + new ScheduledJob( + new IntervalTrigger(2, 10), () -> new SimpleTask(reportIds.incrementAndGet(), 2, 2)), + new ScheduledJob(new ConditionTrigger(backup::isComplete), () -> new SimpleTask(3, 3))); + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/ConditionTrigger.java b/scheduler/src/main/java/com/iluwatar/scheduler/ConditionTrigger.java new file mode 100644 index 000000000000..b06c3346984d --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/ConditionTrigger.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.function.BooleanSupplier; + +/** Fires once, the first time a condition becomes true, such as another task completing. */ +public class ConditionTrigger implements Trigger { + private final BooleanSupplier condition; + private boolean fired; + + public ConditionTrigger(BooleanSupplier condition) { + this.condition = condition; + } + + @Override + public boolean fires(int time) { + if (fired || !condition.getAsBoolean()) { + return false; + } + fired = true; + return true; + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/FirstComeFirstServedScheduler.java b/scheduler/src/main/java/com/iluwatar/scheduler/FirstComeFirstServedScheduler.java new file mode 100644 index 000000000000..ba7b22030b4e --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/FirstComeFirstServedScheduler.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.ArrayDeque; +import java.util.Queue; + +/** Tasks run to completion in the order they arrive. */ +public class FirstComeFirstServedScheduler implements TaskScheduler { + private final Queue taskQueue = new ArrayDeque<>(); + + @Override + public void scheduleTask(Task task) { + taskQueue.add(task); + } + + @Override + public void update(int deltaTime) { + var task = taskQueue.peek(); + if (task == null) { + return; + } + task.execute(deltaTime); + if (task.isComplete()) { + taskQueue.remove(); + } + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/IntervalTrigger.java b/scheduler/src/main/java/com/iluwatar/scheduler/IntervalTrigger.java new file mode 100644 index 000000000000..9689e0877122 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/IntervalTrigger.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +/** Fires at {@code start} and then every {@code period} time units, like a cron job. */ +public record IntervalTrigger(int start, int period) implements Trigger { + + /** Validate the period so that the trigger cannot divide by zero. */ + public IntervalTrigger { + if (period <= 0) { + throw new IllegalArgumentException("Period must be positive"); + } + } + + @Override + public boolean fires(int time) { + return time >= start && (time - start) % period == 0; + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/PriorityScheduler.java b/scheduler/src/main/java/com/iluwatar/scheduler/PriorityScheduler.java new file mode 100644 index 000000000000..2b132b899360 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/PriorityScheduler.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Queue; + +/** + * The task with the highest priority runs first; a newly arrived task with a higher priority + * preempts the running one. Ties go to the task created first. + */ +public class PriorityScheduler implements TaskScheduler { + private final Queue taskQueue = + new PriorityQueue<>( + Comparator.comparingInt(Task::getPriority).reversed().thenComparingInt(Task::getId)); + + @Override + public void scheduleTask(Task task) { + taskQueue.add(task); + } + + @Override + public void update(int deltaTime) { + var task = taskQueue.peek(); + if (task == null) { + return; + } + task.execute(deltaTime); + if (task.isComplete()) { + taskQueue.remove(); + } + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/RoundRobinScheduler.java b/scheduler/src/main/java/com/iluwatar/scheduler/RoundRobinScheduler.java new file mode 100644 index 000000000000..b41dbda2031b --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/RoundRobinScheduler.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.ArrayDeque; +import java.util.Queue; + +/** + * Tasks run in a cyclic order, each getting one time quantum before going to the back of the queue. + */ +public class RoundRobinScheduler implements TaskScheduler { + private final Queue taskQueue = new ArrayDeque<>(); + + @Override + public void scheduleTask(Task task) { + taskQueue.add(task); + } + + @Override + public void update(int deltaTime) { + var task = taskQueue.poll(); + if (task == null) { + return; + } + task.execute(deltaTime); + if (!task.isComplete()) { + taskQueue.add(task); + } + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/ScheduledJob.java b/scheduler/src/main/java/com/iluwatar/scheduler/ScheduledJob.java new file mode 100644 index 000000000000..b5f42c28185d --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/ScheduledJob.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.function.Supplier; + +/** + * Pairs a trigger with the task it creates. A factory is used because a repeating trigger needs a + * fresh task each time it fires. + */ +public record ScheduledJob(Trigger trigger, Supplier taskFactory) { + + /** A job that hands the given task to the scheduler once, at the given time. */ + public static ScheduledJob at(int time, Task task) { + return new ScheduledJob(new TimeTrigger(time), () -> task); + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstScheduler.java b/scheduler/src/main/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstScheduler.java new file mode 100644 index 000000000000..d8cc48ab0709 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstScheduler.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Queue; + +/** + * The task with the shortest remaining time runs next, so short tasks preempt long ones. Ties go to + * the task created first. + */ +public class ShortestRemainingTimeFirstScheduler implements TaskScheduler { + private final Queue taskQueue = + new PriorityQueue<>( + Comparator.comparingInt(Task::getRemainingTime).thenComparingInt(Task::getId)); + + @Override + public void scheduleTask(Task task) { + taskQueue.add(task); + } + + @Override + public void update(int deltaTime) { + // Poll and re-add: the remaining time is the queue key and changes on every run. + var task = taskQueue.poll(); + if (task == null) { + return; + } + task.execute(deltaTime); + if (!task.isComplete()) { + taskQueue.add(task); + } + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/SimpleTask.java b/scheduler/src/main/java/com/iluwatar/scheduler/SimpleTask.java new file mode 100644 index 000000000000..e0d9d1bfe2eb --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/SimpleTask.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import lombok.extern.slf4j.Slf4j; + +/** A task whose work is only to report its progress, such as a placeholder or a timed job. */ +@Slf4j +public class SimpleTask extends AbstractTask { + + public SimpleTask(int id, int totalExecutionTime) { + this(id, totalExecutionTime, 0); + } + + public SimpleTask(int id, int totalExecutionTime, int priority) { + super(id, totalExecutionTime, priority); + } + + @Override + protected void doWork(int units) { + LOGGER.info( + "Task {} is {}/{} complete", getId(), getElapsedTime() + units, getTotalExecutionTime()); + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/Simulator.java b/scheduler/src/main/java/com/iluwatar/scheduler/Simulator.java new file mode 100644 index 000000000000..ed40a3c97da0 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/Simulator.java @@ -0,0 +1,91 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The execution context: advances a clock, fires the triggers of each job, hands the created tasks + * to the scheduler and records when each task completes. + */ +public class Simulator { + private final TaskScheduler scheduler; + private final List jobs; + private final int deltaTime; + private final int simulateTime; + + /** + * Create a simulator. + * + * @param scheduler the scheduling strategy under test + * @param jobs the jobs whose triggers create tasks; jobs firing at the same time are scheduled in + * list order + * @param deltaTime time units the scheduler runs per step + * @param simulateTime total time units to simulate + */ + public Simulator( + TaskScheduler scheduler, List jobs, int deltaTime, int simulateTime) { + if (deltaTime <= 0) { + throw new IllegalArgumentException("Delta time must be positive"); + } + this.scheduler = scheduler; + this.jobs = List.copyOf(jobs); + this.deltaTime = deltaTime; + this.simulateTime = simulateTime; + } + + /** + * Run the simulation. + * + * @return task ids in the order they completed, each mapped to the time it completed + */ + public Map simulate() { + Map completedAt = new LinkedHashMap<>(); + List running = new ArrayList<>(); + for (var time = 0; time < simulateTime; time += deltaTime) { + for (var job : jobs) { + if (job.trigger().fires(time)) { + var task = job.taskFactory().get(); + running.add(task); + scheduler.scheduleTask(task); + } + } + scheduler.update(deltaTime); + var finishedAt = time + deltaTime; + running.removeIf( + task -> { + if (task.isComplete()) { + completedAt.put(task.getId(), finishedAt); + return true; + } + return false; + }); + } + return completedAt; + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/SumTask.java b/scheduler/src/main/java/com/iluwatar/scheduler/SumTask.java new file mode 100644 index 000000000000..d2ef5267ba27 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/SumTask.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** + * A task that computes the sum of 1..n, adding one number per time unit, so the work can be paused + * and resumed between time slices. + */ +@Slf4j +public class SumTask extends AbstractTask { + @Getter private long sum; + private int next = 1; + + public SumTask(int id, int n) { + this(id, n, 0); + } + + public SumTask(int id, int n, int priority) { + super(id, n, priority); + } + + @Override + protected void doWork(int units) { + for (var i = 0; i < units; i++) { + sum += next++; + } + LOGGER.info("Task {} summed up to {}: {}", getId(), next - 1, sum); + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/Task.java b/scheduler/src/main/java/com/iluwatar/scheduler/Task.java new file mode 100644 index 000000000000..dec23a57ce2d --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/Task.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +/** + * A unit of work the scheduler can run in slices of time. Implementations decide what the work is; + * the scheduler only needs to know how much time is left and whether the task is done. + */ +public interface Task { + + /** Unique id of the task. A lower id means the task was created earlier. */ + int getId(); + + /** Priority of the task. The higher the number, the higher the priority. */ + int getPriority(); + + /** Time units the task still needs before it is complete. */ + int getRemainingTime(); + + /** Whether the task has finished all of its work. */ + boolean isComplete(); + + /** + * Run the task for the given number of time units. + * + * @throws IllegalStateException if the task is already complete + */ + void execute(int deltaTime); +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/TaskScheduler.java b/scheduler/src/main/java/com/iluwatar/scheduler/TaskScheduler.java new file mode 100644 index 000000000000..9bc8b6c41b9f --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/TaskScheduler.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +/** The scheduler decides which task runs next and for how long. */ +public interface TaskScheduler { + + /** Add a task to the scheduler. */ + void scheduleTask(Task task); + + /** Run the scheduled tasks for the given number of time units. */ + void update(int deltaTime); +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/TimeTrigger.java b/scheduler/src/main/java/com/iluwatar/scheduler/TimeTrigger.java new file mode 100644 index 000000000000..8c59f2083305 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/TimeTrigger.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +/** Fires once, at a fixed point in time. */ +public record TimeTrigger(int time) implements Trigger { + + @Override + public boolean fires(int currentTime) { + return currentTime == time; + } +} diff --git a/scheduler/src/main/java/com/iluwatar/scheduler/Trigger.java b/scheduler/src/main/java/com/iluwatar/scheduler/Trigger.java new file mode 100644 index 000000000000..a3dfd1c12676 --- /dev/null +++ b/scheduler/src/main/java/com/iluwatar/scheduler/Trigger.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +/** Decides when a job should hand a new task to the scheduler. */ +public interface Trigger { + + /** Whether the trigger fires at the given simulation time. */ + boolean fires(int time); +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/AppTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/AppTest.java new file mode 100644 index 000000000000..0b9b595afaf7 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/AppTest.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } + + @Test + void workloadRunsEveryTriggerType() { + var completedAt = + new Simulator(new FirstComeFirstServedScheduler(), App.workload(), 1, 30).simulate(); + // backup, sum, three interval reports and the cleanup that waits for the backup + assertEquals(6, completedAt.size()); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/FirstComeFirstServedSchedulerTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/FirstComeFirstServedSchedulerTest.java new file mode 100644 index 000000000000..c31c7f3639d9 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/FirstComeFirstServedSchedulerTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class FirstComeFirstServedSchedulerTest { + @Test + void testExecuteTasksFromBeginning() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(0, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(0, new SimpleTask(3, 4))); + + Simulator simulator = new Simulator(new FirstComeFirstServedScheduler(), jobs, 1, 100); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(3, taskCompletedOrder.size()); + assertIterableEquals(List.of(1, 2, 3), taskCompletedOrder.keySet()); + assertEquals(3, taskCompletedOrder.get(1)); + assertEquals(5, taskCompletedOrder.get(2)); + assertEquals(9, taskCompletedOrder.get(3)); + } + + @Test + void testExecuteTasks() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(1, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(6, new SimpleTask(3, 4))); + jobs.add(ScheduledJob.at(7, new SimpleTask(4, 2))); + jobs.add(ScheduledJob.at(8, new SimpleTask(5, 1))); + + Simulator simulator = new Simulator(new FirstComeFirstServedScheduler(), jobs, 1, 100); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(5, taskCompletedOrder.size()); + assertIterableEquals(List.of(1, 2, 3, 4, 5), taskCompletedOrder.keySet()); + assertEquals(3, taskCompletedOrder.get(1)); + assertEquals(5, taskCompletedOrder.get(2)); + assertEquals(10, taskCompletedOrder.get(3)); + assertEquals(12, taskCompletedOrder.get(4)); + assertEquals(13, taskCompletedOrder.get(5)); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/PrioritySchedulerTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/PrioritySchedulerTest.java new file mode 100644 index 000000000000..2f16204c7e62 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/PrioritySchedulerTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class PrioritySchedulerTest { + @Test + void testExecuteTasksFromBeginning() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3, 0))); + jobs.add(ScheduledJob.at(0, new SimpleTask(2, 2, 2))); + jobs.add(ScheduledJob.at(0, new SimpleTask(3, 1, 1))); + + Simulator simulator = new Simulator(new PriorityScheduler(), jobs, 1, 10); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(3, taskCompletedOrder.size()); + assertIterableEquals(List.of(2, 3, 1), taskCompletedOrder.keySet()); + assertEquals(2, taskCompletedOrder.get(2)); + assertEquals(3, taskCompletedOrder.get(3)); + assertEquals(6, taskCompletedOrder.get(1)); + } + + @Test + void testExecuteTasks() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3, 1))); + jobs.add(ScheduledJob.at(1, new SimpleTask(2, 2, 0))); + jobs.add(ScheduledJob.at(2, new SimpleTask(3, 4, 5))); + jobs.add(ScheduledJob.at(7, new SimpleTask(4, 2, 4))); + jobs.add(ScheduledJob.at(8, new SimpleTask(5, 1, 2))); + + Simulator simulator = new Simulator(new PriorityScheduler(), jobs, 1, 100); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(5, taskCompletedOrder.size()); + assertIterableEquals(List.of(3, 1, 4, 5, 2), taskCompletedOrder.keySet()); + assertEquals(6, taskCompletedOrder.get(3)); + assertEquals(7, taskCompletedOrder.get(1)); + assertEquals(9, taskCompletedOrder.get(4)); + assertEquals(10, taskCompletedOrder.get(5)); + assertEquals(12, taskCompletedOrder.get(2)); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/RoundRobinSchedulerTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/RoundRobinSchedulerTest.java new file mode 100644 index 000000000000..bd665d4ab675 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/RoundRobinSchedulerTest.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class RoundRobinSchedulerTest { + @Test + void testExecuteTasksFromBeginning() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(0, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(0, new SimpleTask(3, 4))); + + Simulator simulator = new Simulator(new RoundRobinScheduler(), jobs, 1, 10); + + Map taskCompletedOrder = simulator.simulate(); + assertEquals(3, taskCompletedOrder.size()); + assertIterableEquals(List.of(2, 1, 3), taskCompletedOrder.keySet()); + assertEquals(5, taskCompletedOrder.get(2)); + assertEquals(7, taskCompletedOrder.get(1)); + assertEquals(9, taskCompletedOrder.get(3)); + } + + @Test + void testExecuteTasks() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(1, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(2, new SimpleTask(3, 4))); + jobs.add(ScheduledJob.at(7, new SimpleTask(4, 2))); + jobs.add(ScheduledJob.at(8, new SimpleTask(5, 1))); + + Simulator simulator = new Simulator(new RoundRobinScheduler(), jobs, 1, 100); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(5, taskCompletedOrder.size()); + assertIterableEquals(List.of(1, 2, 3, 5, 4), taskCompletedOrder.keySet()); + assertEquals(4, taskCompletedOrder.get(1)); + assertEquals(6, taskCompletedOrder.get(2)); + assertEquals(10, taskCompletedOrder.get(3)); + assertEquals(11, taskCompletedOrder.get(5)); + assertEquals(12, taskCompletedOrder.get(4)); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstSchedulerTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstSchedulerTest.java new file mode 100644 index 000000000000..408d6c239961 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/ShortestRemainingTimeFirstSchedulerTest.java @@ -0,0 +1,71 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class ShortestRemainingTimeFirstSchedulerTest { + @Test + void testExecuteTasksFromBeginning() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(0, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(0, new SimpleTask(3, 4))); + + Simulator simulator = new Simulator(new ShortestRemainingTimeFirstScheduler(), jobs, 1, 10); + + Map taskCompletedOrder = simulator.simulate(); + assertEquals(3, taskCompletedOrder.size()); + assertIterableEquals(List.of(2, 1, 3), taskCompletedOrder.keySet()); + } + + @Test + void testExecuteTasks() { + List jobs = new ArrayList<>(); + jobs.add(ScheduledJob.at(0, new SimpleTask(1, 3))); + jobs.add(ScheduledJob.at(1, new SimpleTask(2, 2))); + jobs.add(ScheduledJob.at(2, new SimpleTask(3, 4))); + jobs.add(ScheduledJob.at(7, new SimpleTask(4, 2))); + jobs.add(ScheduledJob.at(8, new SimpleTask(5, 1))); + + Simulator simulator = new Simulator(new ShortestRemainingTimeFirstScheduler(), jobs, 1, 100); + + Map taskCompletedOrder = simulator.simulate(); + + assertEquals(5, taskCompletedOrder.size()); + assertIterableEquals(List.of(1, 2, 3, 5, 4), taskCompletedOrder.keySet()); + assertEquals(3, taskCompletedOrder.get(1)); + assertEquals(5, taskCompletedOrder.get(2)); + assertEquals(9, taskCompletedOrder.get(3)); + assertEquals(10, taskCompletedOrder.get(5)); + assertEquals(12, taskCompletedOrder.get(4)); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/SimulatorTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/SimulatorTest.java new file mode 100644 index 000000000000..1e399bb7cb60 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/SimulatorTest.java @@ -0,0 +1,70 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class SimulatorTest { + + @Test + void intervalTriggerSchedulesFreshTaskEachPeriod() { + var ids = new AtomicInteger(); + var job = + new ScheduledJob(new IntervalTrigger(0, 5), () -> new SimpleTask(ids.incrementAndGet(), 1)); + + var completedAt = + new Simulator(new FirstComeFirstServedScheduler(), List.of(job), 1, 15).simulate(); + + assertEquals(Map.of(1, 1, 2, 6, 3, 11), completedAt); + } + + @Test + void conditionTriggerStartsTaskAfterAnotherCompletes() { + var first = new SimpleTask(1, 2); + var jobs = + List.of( + ScheduledJob.at(0, first), + new ScheduledJob(new ConditionTrigger(first::isComplete), () -> new SimpleTask(2, 1))); + + var completedAt = new Simulator(new FirstComeFirstServedScheduler(), jobs, 1, 10).simulate(); + + assertEquals(List.of(1, 2), List.copyOf(completedAt.keySet())); + assertEquals(2, completedAt.get(1)); + assertEquals(3, completedAt.get(2)); + } + + @Test + void simulatorRejectsNonPositiveDeltaTime() { + var scheduler = new FirstComeFirstServedScheduler(); + List jobs = List.of(); + assertThrows(IllegalArgumentException.class, () -> new Simulator(scheduler, jobs, 0, 10)); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/TaskTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/TaskTest.java new file mode 100644 index 000000000000..1a7d8478512f --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/TaskTest.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class TaskTest { + + @Test + void taskCompletesAfterItsExecutionTime() { + var task = new SimpleTask(1, 3, 2); + task.execute(2); + assertFalse(task.isComplete()); + assertEquals(1, task.getRemainingTime()); + task.execute(1); + assertTrue(task.isComplete()); + assertEquals(0, task.getRemainingTime()); + assertEquals(2, task.getPriority()); + } + + @Test + void executingCompletedTaskThrows() { + var task = new SimpleTask(1, 1); + task.execute(1); + assertThrows(IllegalStateException.class, () -> task.execute(1)); + } + + @Test + void taskRejectsNonPositiveExecutionTime() { + assertThrows(IllegalArgumentException.class, () -> new SimpleTask(1, 0)); + } + + @Test + void sumTaskResumesWorkAcrossSlices() { + var task = new SumTask(1, 10); + task.execute(4); + assertEquals(10, task.getSum()); + task.execute(100); + assertEquals(55, task.getSum()); + assertTrue(task.isComplete()); + } +} diff --git a/scheduler/src/test/java/com/iluwatar/scheduler/TriggerTest.java b/scheduler/src/test/java/com/iluwatar/scheduler/TriggerTest.java new file mode 100644 index 000000000000..232d3e7a2470 --- /dev/null +++ b/scheduler/src/test/java/com/iluwatar/scheduler/TriggerTest.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * 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.iluwatar.scheduler; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +class TriggerTest { + + @Test + void timeTriggerFiresOnlyAtItsTime() { + var trigger = new TimeTrigger(3); + assertFalse(trigger.fires(2)); + assertTrue(trigger.fires(3)); + assertFalse(trigger.fires(4)); + } + + @Test + void intervalTriggerFiresEveryPeriodFromStart() { + var trigger = new IntervalTrigger(2, 5); + assertFalse(trigger.fires(0)); + assertTrue(trigger.fires(2)); + assertFalse(trigger.fires(5)); + assertTrue(trigger.fires(7)); + assertTrue(trigger.fires(12)); + } + + @Test + void intervalTriggerRejectsNonPositivePeriod() { + assertThrows(IllegalArgumentException.class, () -> new IntervalTrigger(0, 0)); + } + + @Test + void conditionTriggerFiresOnceWhenConditionHolds() { + var condition = new AtomicBoolean(false); + var trigger = new ConditionTrigger(condition::get); + assertFalse(trigger.fires(0)); + condition.set(true); + assertTrue(trigger.fires(1)); + assertFalse(trigger.fires(2)); + } +}