By Mateusz Jasiński · Updated
Writing a Folia plugin: schedulers, threads and folia-supported
Fileplugin.ymlFilepaper-plugin.ymlTo make a plugin Folia compatible, add folia-supported: true to plugin.yml or paper-plugin.yml, then replace every Bukkit scheduler call with one of the four region-aware schedulers: global for server-wide work, region for blocks at a location, entity for a player or mob, async for work off the tick. Teleport with teleportAsync, touch an entity or block only from the thread of the region that owns it, and treat any state shared between players as shared between threads. Paper has had the same scheduler API since its 1.20.1 builds, so one jar runs on both.
Declare folia-supported
Folia skips any plugin without the flag and prints Could not load plugin 'MyPlugin v1.0.0' as it is not marked as supporting Folia!. The key is the same in both files:
name: MyPlugin
version: 1.0.0
main: com.example.myplugin.MyPlugin
api-version: '1.20'
folia-supported: truePaper's docs say marking the plugin is "not nearly enough". The flag gets you past the loader. Everything below is what keeps the plugin from throwing once it runs.
Why the Bukkit scheduler throws on Folia
Folia has no main thread. It groups nearby loaded chunks into regions and ticks each region on its own thread, in parallel. A runTask call means "run this on the main thread", and there is no such thread to run it on, so Folia makes CraftScheduler.handle throw a bare UnsupportedOperationException. Every runTask, runTaskLater, runTaskTimer and BukkitRunnable hits it, the async variants too. Server owners usually see this as the "marked but not ported" error from the Folia plugin list.
Old Bukkit call to Folia replacement
| Bukkit / Paper call | Folia replacement |
|---|---|
Bukkit.getScheduler().runTask(plugin, r) | entity.getScheduler().run(plugin, task -> ..., null) for an entity, Bukkit.getRegionScheduler().execute(plugin, location, r) for a block, Bukkit.getGlobalRegionScheduler().execute(plugin, r) for neither |
runTaskLater(plugin, r, delay) | runDelayed(...) on the same three, with delayTicks last |
runTaskTimer(plugin, r, 0L, 20L) | runAtFixedRate(..., 1L, 20L), initial delay at least 1 |
runTaskAsynchronously(plugin, r) | Bukkit.getAsyncScheduler().runNow(plugin, task -> ...) |
runTaskTimerAsynchronously(plugin, r, 0L, 20L) | Bukkit.getAsyncScheduler().runAtFixedRate(plugin, task -> ..., 0L, 1L, TimeUnit.SECONDS) |
BukkitTask.cancel() | ScheduledTask.cancel(), or task.cancel() inside the lambda |
Bukkit.getScheduler().cancelTasks(plugin) | cancelTasks(plugin) on the global and async schedulers; keep handles for region and entity tasks |
entity.teleport(location) | entity.teleportAsync(location) |
Bukkit.isPrimaryThread() | Bukkit.isOwnedByCurrentRegion(entity) or (location), Bukkit.isGlobalTickThread() |
world.setTime, setStorm from any task | The same call, run on the global region scheduler |
Each task is a Consumer<ScheduledTask>, so a repeating task can cancel itself without a BukkitRunnable.
The four schedulers
Config keyio.papermc.paper.threadedregions.schedulerAll four live in io.papermc.paper.threadedregions.scheduler. Pick by what the task touches, not by how often it runs.
GlobalRegionScheduler: work that belongs to no region
The global region owns day time, weather, console commands and other server-wide state. On Folia, setTime or setStorm from anywhere else throws Cannot modify weather off of the global region.
Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin,
task -> Bukkit.getWorlds().forEach(world -> world.setStorm(false)),
1L, 20L * 60);Do not use it to reach players or blocks. It does not own them either.
RegionScheduler: blocks at a location
It runs the task on whichever region owns the chunk at that location:
Location spot = new Location(world, 1200, 64, -340);
Bukkit.getRegionScheduler().execute(plugin, spot, () -> spot.getBlock().setType(Material.BEEHIVE));
Bukkit.getRegionScheduler().runDelayed(plugin, spot,
task -> spot.getBlock().setType(Material.AIR), 100L);The Javadoc is direct about entities: "It is entirely inappropriate to use the region scheduler to schedule tasks for entities." An entity can walk into another region before the task runs.
EntityScheduler: a player or a mob
entity.getScheduler() follows the entity across regions and worlds and always runs on its current owner. It takes an extra retired callback, which runs instead of the task if the entity is removed first, for a player that means logging out:
ScheduledTask task = player.getScheduler().runAtFixedRate(plugin,
t -> player.sendActionBar(Component.text("Wave " + arena.wave())),
() -> arena.leave(player.getUniqueId()),
1L, 20L);
if (task == null) {
return;
}run, runDelayed and runAtFixedRate return null when the entity is already gone, so check it. Keep the retired callback small: the Javadoc says it must not remove entities, load chunks or change ticket levels. Pass null if you have nothing to clean up.
AsyncScheduler: off the tick
Database calls, HTTP, file I/O. Delays here are in a TimeUnit, not ticks. Bring the result back through the scheduler of whatever you want to change:
UUID id = player.getUniqueId();
Bukkit.getAsyncScheduler().runNow(plugin, task -> {
PlayerStats stats = database.load(id);
player.getScheduler().run(plugin, t -> stats.applyTo(player), null);
});Never read a block or an entity from an async task. On Paper that was a bad habit; on Folia it throws.
teleportAsync
Entity#teleport throws Must use teleportAsync while in region threading, and the Folia README says it will never come back. teleportAsync loads the target chunk and moves the entity, handing it to the destination region:
player.teleportAsync(target, PlayerTeleportEvent.TeleportCause.COMMAND).thenAccept(success -> {
if (!success) {
return;
}
player.getScheduler().run(plugin, t -> player.sendMessage(Component.text("Teleported")), null);
});You can call it from any thread. Folia's implementation runs it right away if the current region owns the entity, otherwise it schedules it on the entity's scheduler. The future completes with false if the entity was removed in between. Do the follow-up through the entity scheduler rather than relying on which thread finishes the future.
Bukkit.isOwnedByCurrentRegion
Bukkit.isOwnedByCurrentRegion tells you whether the thread you are on owns an entity, a block, a location or a chunk area. It has overloads for Entity, Block, Location, World plus chunk coordinates, and versions with a chunk radius. Use it to skip a scheduler hop when you already own the target:
void setBlock(Location location, Material type) {
if (Bukkit.isOwnedByCurrentRegion(location)) {
location.getBlock().setType(type);
return;
}
Bukkit.getRegionScheduler().execute(plugin, location, () -> location.getBlock().setType(type));
}On Paper it returns true on the main thread, so the same code takes the direct path there.
Reaching other regions' entities and blocks
A region owns its own chunks and the entities in them. The README says you can usually assume about 8 chunks around an event's source are owned, and warns that this is not guaranteed. Anything further away, like another player's location for a /whereis command, has to be read on that player's region:
target.getScheduler().run(plugin, t -> {
Location where = target.getLocation();
viewer.getScheduler().run(plugin, t2 ->
viewer.sendMessage(Component.text(target.getName() + " is at " + where.getBlockX() + ", " + where.getBlockZ())), null);
}, null);Copy plain values out (the Location, numbers, strings) and pass those back. Do not carry a Block or Chunk over and read it on the other side. For something that spans a large area, like a paste or an explosion, either split it per region or wait until one region owns it all, and check with the radius overload of isOwnedByCurrentRegion.
Events run on the owning region
There is no single event thread any more. From the Folia README:
- An event about one entity, a block break for example, fires on the region that owns that entity.
- An event acting on an entity, like damage, fires on the region that owns the target.
- Events from regions and the global region all count as synchronous; the async flag on them is deprecated.
- Player commands run on the player's region, console commands on the global region.
So two BlockBreakEvents from players far apart run on two threads at the same moment, and inside a handler you only own what is near the event. A console command handler that changes a player has to go through player.getScheduler().
Shared state and thread safety
The README puts it plainly: regions run in parallel, and sharing data between them can corrupt it. Every field your listeners and tasks touch from more than one region needs to be safe for that.
private final Map<UUID, Integer> blocksBroken = new ConcurrentHashMap<>();
@EventHandler
public void onBreak(BlockBreakEvent event) {
blocksBroken.merge(event.getPlayer().getUniqueId(), 1, Integer::sum);
}- Use
ConcurrentHashMapand its atomic methods (merge,compute,computeIfAbsent).getthenputis a race even on a concurrent map. - Use
AtomicIntegerandAtomicLongfor counters, notintfields. - Static mutable fields, plain
HashMaps andArrayLists in a manager are the usual source of rare, unreproducible bugs. Make them final and concurrent, or keep the data on one owner and only reach it through that owner's scheduler. - Do not cache
Block,ChunkorWorldlookups and read them later from somewhere else. Cache coordinates. - Folia lists the whole scoreboard API as broken, and
registerNewObjectivethrowsUnsupportedOperationException. Use the action bar, tab list or boss bars for HUDs. - Worlds cannot be created or unloaded at runtime.
createWorldandunloadWorldthrow.
One jar for Paper and Folia
Paper took the Folia scheduler API in June 2023 (Paper PR #9360), on the 1.20.1 builds. On Paper all four still work: the tick schedulers run their tasks on the main thread and the region scheduler simply hands off to the global one, so code written for Folia behaves the same there. No reflection and no wrapper is needed for Paper 1.20.1 and newer.
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
dependencies {
compileOnly("io.papermc.paper:paper-api:26.3.build.+")
}Compile against the oldest Paper you want to load on. The 26.x API needs Java 25, so a jar built against it will not start on a 1.21 server running Java 21. For 1.21.11 and older the version is written as 1.21.11-R0.1-SNAPSHOT. Spigot does not have these schedulers, so a jar that uses them is a Paper and Folia jar.
When you need to branch, for a feature Folia lacks such as world loading, Paper's docs check the brand:
boolean folia = ServerBuildInfo.buildInfo().isBrandCompatible(Key.key("papermc", "folia"));On builds without ServerBuildInfo, checking for the class io.papermc.paper.threadedregions.RegionizedServer works too. It exists on Folia and not on Paper.
Common console errors and what they mean
| Console | Cause | Fix |
|---|---|---|
Could not load plugin '...' as it is not marked as supporting Folia! | No folia-supported: true | Add the flag |
java.lang.UnsupportedOperationException with CraftScheduler.handle in the trace | A Bukkit scheduler call | Move it to one of the four schedulers |
UnsupportedOperationException: Must use teleportAsync while in region threading | teleport | teleportAsync |
IllegalStateException: Thread failed main thread check: Accessing entity state off owning region's thread | An entity read or changed from another region or an async task | Go through entity.getScheduler() |
Thread failed main thread check: Cannot read world asynchronously or Cannot modify world asynchronously | A block outside the current region | getRegionScheduler() for that location |
Cannot modify weather off of the global region, Cannot modify time off of the global region | World-wide state from a region thread | getGlobalRegionScheduler() |
IllegalArgumentException: Initial delay ticks may not be <= 0 | runAtFixedRate(..., 0L, 20L) ported straight from runTaskTimer | Start at 1L |
UnsupportedOperationException from registerNewObjective | Scoreboard API | Use another HUD |
The thread-check errors are logged with the full context first: thread name, the region's center chunk and the entity or block position. That line tells you which region tried to touch what.
Test on a real Folia server
Most threading bugs only show when two regions run at once, so a single player at spawn proves very little. Run a real Folia build, put players or bots in places far enough apart to be separate regions, and use every feature from each of them while you watch the console. A thread-check error is a failed test even if the feature looked fine.
Testing a Paper plugin with real bots covers doing this from scenario files or JUnit 5 and in CI, where an error in the server log fails the run. IgniteTestTool bots join Folia servers too, its server agent reads entities and blocks on the thread that owns them, and its health check reports TPS and MSPT per region. For load on top of that, see load testing a server with bots.
If you run the server rather than write the plugins, Folia vs Paper and migrating a Paper server to Folia cover the other side.
Common questions
How do I make my plugin Folia compatible?
Add folia-supported: true to plugin.yml or paper-plugin.yml, replace every Bukkit scheduler call with the global, region, entity or async scheduler, use teleportAsync instead of teleport, and only touch an entity or block from the region that owns it. Then test on a real Folia server with players far apart.
Why does the Bukkit scheduler throw UnsupportedOperationException on Folia?
Folia has no main thread, so runTask and the other BukkitScheduler methods have nowhere to run. Folia makes CraftScheduler.handle throw UnsupportedOperationException. Use the GlobalRegionScheduler, RegionScheduler, EntityScheduler or AsyncScheduler instead.
Which Folia scheduler should I use?
The entity scheduler (entity.getScheduler()) for anything about a player or mob, the region scheduler for blocks at a location, the global region scheduler for world time, weather and other server-wide work, and the async scheduler for database or web calls that do not touch the world.
Can one plugin jar support both Paper and Folia?
Yes. Paper has had the same four schedulers since its 1.20.1 builds and runs their tasks on the main thread, so code written for Folia works on Paper unchanged. Compile against the oldest Paper version you support and add folia-supported: true.
What does Thread failed main thread check mean on Folia?
Code read or changed an entity or block from a thread that does not own it: another region or an async task. The message names the entity or block position. Move that code onto the entity's scheduler or the region scheduler for that location.
Where to go next
Written from
- Paper docs: supporting Paper and Folia
- Folia README: regions, events, broken API, teleportAsync
- Paper javadoc: RegionScheduler
- Paper javadoc: EntityScheduler and the retired callback
- Paper javadoc: GlobalRegionScheduler
- Paper javadoc: AsyncScheduler
- Paper javadoc: Bukkit.isOwnedByCurrentRegion overloads
- Paper javadoc: Entity.teleportAsync
- Paper javadoc: ServerBuildInfo.isBrandCompatible
- Paper PR #9360: Folia scheduler API moved to Paper (June 2023, 1.20.1)
- Folia source: CraftScheduler, teleport and thread check errors
- Folia issue #155: the not marked as supporting Folia error
- Paper docs: project setup, paper-api dependency and Java 25