-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
194: Practice Exercise: Building a Simple Task Scheduler with ZIO
A few years ago, I was reviewing a PR from a developer who was trying to build a "cleanup" utility for a legacy system. He had a list of about 10,000 stale records to archive, and his solution was to loop through that list and wrap each archive call in a Scala Future. On his local machine with ten records, it worked beautifully. In production, it was a disaster. The application didn't just slow down; it crashed with an OutOfMemoryError because it tried to spawn thousands of futures simultaneously, overwhelming the execution context and the database connection pool.
That's the danger of "fire and forget" concurrency without a proper strategy. When you're building a task scheduler, you aren't just worried about *if* a task runs, but *how* and *when* it runs. This is where ZIO really shines. Unlike standard Futures, ZIO fibers are lightweight, and the library gives us the primitives to control concurrency, manage state, and handle interruptions without losing our minds to race conditions.
Orchestrating Execution with Fibers and Sleep
In a ZIO-based scheduler, we don't block threads. If a task needs to run in five minutes, we don't use Thread.sleep()—which would hold a thread hostage—we use ZIO.sleep. This tells the ZIO runtime to "wake this fiber up" later, freeing the underlying thread to do other useful work in the meantime. I've seen developers try to implement their own timer loops using while(true) and Thread.sleep, and it's almost always a recipe for a deadlock or a memory leak.
To actually run these tasks in the background, we use fork. When you fork an effect, ZIO creates a fiber—a lightweight "green thread." If you have a list of tasks to trigger, you can use ZIO.foreachPar to run them in parallel, but be careful. If you're dealing with 10,000 tasks like our unlucky friend from the anecdote, you'll want to use a Semaphore to limit the number of concurrent executions. It's a simple way to say, "I don't care how many tasks are queued; only five can talk to the database at once."
Managing Scheduler State with Ref and Queue
A scheduler isn't very useful if it can't keep track of what it's doing. You'll likely need a way to store pending tasks or track the status of completed ones. In the ZIO world, we avoid var and synchronized blocks. Instead, we use Ref for shared, mutable state. A Ref is essentially a thread-safe wrapper around a value that allows you to perform atomic updates.
For a more robust scheduler, I usually recommend a Queue. A Queue allows one part of your application to "push" a task into the scheduler while a separate "worker" fiber sits in a loop, pulling tasks out and executing them. This decouples the request to do work from the actual execution. If the worker crashes or the system slows down, the queue acts as a buffer. It’s a pattern I use in almost every production system I build because it makes the system resilient to spikes in load.
// A quick glimpse at how a worker loop looks
def workerLoop(queue: Queue[TaskDefinition]): ZIO[Any, Throwable, Unit] = {
for {
task <- queue.take // This will suspend the fiber until a task is available
_ <- runTask(task).catchAll(err => ZIO.logError(s"Task failed: $err"))
} yield ()
}.forever // Keep the worker running indefinitely
📋 Practical Task
Building a Priority-Based Background Job Processor
Your goal is to implement a simple task scheduler that can handle jobs with different priority levels. High-priority jobs should be processed before low-priority jobs, and you must ensure that no more than 3 jobs run concurrently to avoid overwhelming the system.
Requirements:
- Define a
Jobcase class that contains aname: String, apriority: Int(where higher is more urgent), and theaction: ZIO[Any, Throwable, Unit]to execute. - Create a
JobSchedulerclass that uses aRefto store a list of pending jobs. - Implement a
submitJob(job: Job)method that adds a job to the pending list. - Implement a
processNextJob()method that:- Finds the job with the highest priority.
- Removes it from the pending list atomically.
- Executes the job.
- Use a
Semaphoreto limit the concurrency ofprocessNextJobexecutions to a maximum of 3. - Write a
mainmethod that submits 10 jobs with varying priorities and delays, then triggers the processing of these jobs in parallel to demonstrate that the priority is respected and the concurrency limit is enforced.
There are no comments for now.