Files
netneutrality/docs/threading.md
T
2026-10-19 08:21:42 -04:00

47 lines
2.3 KiB
Markdown

# Threading & Scheduling
**Packages:** `me.bobert.netneutrality.core.thread` and `me.bobert.netneutrality.core.scheduled`
This subsystem centralizes asynchronous execution and recurring jobs.
## Classes
| Class | Responsibility |
|---|---|
| `ThreadManager` | Static registry of `ExecutorService` instances shared across the bot. |
| `BaseThreadFactory` | Custom `ThreadFactory` giving threads meaningful names and an uncaught-exception handler. |
| `ScheduledTaskManager` | Schedules and cancels recurring [scheduled tasks](tasks.md#34-scheduled-tasks). |
## `ThreadManager`
- `getScheduledExecutor()` — a `ScheduledThreadPool` sized to the number of CPU cores.
- `getExecutor(name)` — returns (and caches) a named thread pool for ad-hoc async work.
- `shutdownExecutor()` — shuts the executors down cleanly; called from
[`App.shutdown()`](architecture.md#shutdown-lifecycle).
## `BaseThreadFactory`
Names created threads (e.g. `pool-1`) so they are identifiable in logs and stack dumps, and installs
an [`ExecutorException`](utilities-and-bootstrap.md#exceptions) as the thread's
`UncaughtExceptionHandler` so crashes on worker threads are still routed through
[`LogHandler`](utilities-and-bootstrap.md#loghandler). It is used by `ThreadManager`; the
[Web API](web-api.md) runs on Javalin's own thread pool instead.
## `ScheduledTaskManager`
Coordinates [`ScheduledTask`](tasks.md#34-scheduled-tasks) instances (discovered reflectively at
startup by [`TaskManager.init()`](tasks.md#taskmanager)):
- `schedule(ScheduledTask task)` — schedules the task at a fixed delay/interval derived from its
`TimeFrame` (minutely / hourly / daily / custom), using the shared scheduled executor.
- `cancelAll()` — cancels every scheduled task; called first in
[`App.shutdown()`](architecture.md#shutdown-lifecycle).
The existing scheduled tasks are `MusicManagerCleanup`, `MusicPlayerAutoDisconnect` (which reads the
bot's gateway voice state rather than JDA's audio manager, see [music.md](music.md)), and
`TaskCleanup` (see the [task catalog](tasks.md#concrete-task-catalog)).
> **Direction of travel:** the scheduled-task abstraction is intended to eventually replace ad-hoc
> threads created via `ThreadManager`, giving a single, uniform way to express recurring background
> work. It is still evolving (see [tasks.md §3.4](tasks.md#34-scheduled-tasks)).