Plugins and extensions

suggest change

A plugin system lets other code add features to your application without changing the application itself. Editors, build tools, CLI tools and servers all use it: IntelliJ IDEA, Gradle and Ktor are built around plugins.

Every plugin system has the same parts:

This article builds these parts step by step in plain Kotlin on the JVM, then shows the configurable "install a plugin" style used by Ktor.

Defining the plugin API

Start with small interfaces. The host gives each plugin a context object instead of handing out the whole application, so plugins can only use what you decided to expose:

interface Plugin {
    val id: String
    fun start(context: PluginContext)
    fun stop() {}
}

interface PluginContext {
    val pluginId: String
    fun registerCommand(name: String, action: (args: List<String>) -> String)
    fun log(message: String)
}

stop() has a default implementation, so plugins that don't hold resources don't have to override it. See Interface with default implementations.

A simple plugin host

The host creates one context per plugin. Because the context knows which plugin it belongs to, the host can record who registered what and report conflicts:

class PluginHost {
    private class Command(val owner: String, val action: (List<String>) -> String)

    private val commands = linkedMapOf<String, Command>()
    private val started = mutableListOf<Plugin>()

    private inner class Context(override val pluginId: String) : PluginContext {
        override fun registerCommand(name: String, action: (List<String>) -> String) {
            val existing = commands[name]
            require(existing == null) { "'$name' is already registered by ${existing?.owner}" }
            commands[name] = Command(pluginId, action)
        }

        override fun log(message: String) = println("[$pluginId] $message")
    }

    fun load(plugin: Plugin) {
        plugin.start(Context(plugin.id))
        started += plugin // only after start() succeeded
    }

    fun execute(line: String): String {
        val parts = line.trim().split(Regex("\\s+"))
        val command = commands[parts.first()] ?: return "unknown command: ${parts.first()}"
        return command.action(parts.drop(1))
    }

    fun commandOwners(): Map<String, String> = commands.mapValues { it.value.owner }

    fun shutdown() {
        // stop in reverse order, like closing nested resources
        started.asReversed().forEach { it.stop() }
        started.clear()
    }
}

Two plugins:

class UpperPlugin : Plugin {
    override val id = "upper"

    override fun start(context: PluginContext) {
        context.registerCommand("upper") { args -> args.joinToString(" ").uppercase() }
        context.log("ready")
    }
}

class MathPlugin : Plugin {
    override val id = "math"

    override fun start(context: PluginContext) {
        context.registerCommand("sum") { args -> args.sumOf { it.toInt() }.toString() }
        context.registerCommand("max") { args -> args.maxOf { it.toInt() }.toString() }
        context.log("registered 2 commands")
    }

    override fun stop() = println("math: stopped")
}

fun main() {
    val host = PluginHost()
    host.load(UpperPlugin())
    host.load(MathPlugin())

    println(host.commandOwners())
    println(host.execute("upper hello plugins"))
    println(host.execute("sum 1 2 3"))
    println(host.execute("max 4 9 2"))
    println(host.execute("reverse abc"))

    host.shutdown()
}
[upper] ready
[math] registered 2 commands
{upper=upper, sum=math, max=math}
HELLO PLUGINS
6
9
unknown command: reverse
math: stopped

Plugins are just classes that implement an interface. Everything else in this article is about how the host finds them and keeps them under control.

Extension points

A command map is one kind of extension point. When you have several, a small generic class avoids writing the same registration code each time:

import java.util.concurrent.CopyOnWriteArrayList

class ExtensionPoint<T : Any>(val name: String) {
    private class Entry<T>(val priority: Int, val extension: T)

    private val entries = CopyOnWriteArrayList<Entry<T>>()

    fun register(extension: T, priority: Int = 0): AutoCloseable {
        val entry = Entry(priority, extension)
        entries += entry
        return AutoCloseable { entries.remove(entry) }
    }

    val extensions: List<T>
        get() = entries.sortedByDescending { it.priority }.map { it.extension }
}

A text processing pipeline built on it:

fun interface TextFilter {
    fun apply(text: String): String
}

val textFilters = ExtensionPoint<TextFilter>("text-filter")

fun render(text: String): String =
    textFilters.extensions.fold(text) { acc, filter -> filter.apply(acc) }

fun main() {
    textFilters.register(TextFilter { it.trim() }, priority = 100)
    textFilters.register(TextFilter { it.replace("kotlin", "Kotlin") })
    val exclaim = textFilters.register(TextFilter { "$it!" }, priority = -10)

    println(render("  i like kotlin  "))

    exclaim.close()
    println(render("  i like kotlin  "))
}
i like Kotlin!
i like Kotlin

A fun interface lets plugins pass a lambda, while the host still gets a named type that is easy to find and document.

Discovering plugins with ServiceLoader

Hard-coding host.load(UpperPlugin()) means the host must know every plugin at compile time. The JDK has a built-in discovery mechanism, java.util.ServiceLoader, which finds implementations listed in META-INF/services files on the classpath.

In the plugin module, add a resource file named after the fully qualified name of the interface:

src/main/resources/META-INF/services/com.example.api.Plugin

Its content is one implementation class per line (# starts a comment):

# plugins provided by this JAR
com.example.plugins.UpperPlugin
com.example.plugins.MathPlugin

The host only knows the interface:

import com.example.api.Plugin
import java.util.ServiceLoader

fun main() {
    val host = PluginHost()
    val plugins = ServiceLoader.load(Plugin::class.java).sortedBy { it.id }
    for (plugin in plugins) host.load(plugin)
    println("loaded: ${plugins.map { it.id }}")
}
[math] registered 2 commands
[upper] ready
loaded: [math, upper]

ServiceLoader is an Iterable, so all collection functions (sortedBy, map, toList) work on it. The order of providers depends on classpath order, so sort them if order matters.

Kotlin pitfall: objects can't be service providers

ServiceLoader creates providers by calling a public no-argument constructor. A Kotlin object has a private constructor, so listing one in META-INF/services fails at runtime:

java.util.ServiceConfigurationError: com.example.api.Plugin:
    com.example.plugins.UpperPlugin Unable to get public no-arg constructor

Use a class. A primary constructor with parameters also fails, unless every parameter has a default value: then the Kotlin compiler generates an extra no-argument constructor for the JVM.

class GreetPlugin(private val greeting: String = "Hello") : Plugin { // OK
    override val id = "greet"
    override fun start(context: PluginContext) {
        context.registerCommand("greet") { args -> "$greeting, ${args.joinToString(" ")}" }
    }
}

Selecting plugins without instantiating them

ServiceLoader.stream() returns ServiceLoader.Provider objects. type() gives the provider class without creating an instance, so you can read metadata from an annotation and only instantiate plugins that are enabled:

import com.example.api.Plugin
import java.util.ServiceLoader

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class PluginInfo(val name: String, val description: String = "")

fun loadEnabled(enabled: Set<String>): List<Plugin> =
    ServiceLoader.load(Plugin::class.java).stream()
        .filter { provider ->
            val name = provider.type().getAnnotation(PluginInfo::class.java)?.name
            name != null && name in enabled
        }
        .map { it.get() } // the constructor runs only here
        .toList()

The set of enabled plugins would typically come from a configuration file or an environment variable. For more on reading annotations at runtime, see Reflection.

Surviving a broken provider

If one listed class is missing or its constructor throws, the iterator throws ServiceConfigurationError (an Error, not an Exception). To skip broken plugins instead of crashing at startup, catch it around each step:

import com.example.api.Plugin
import java.util.ServiceConfigurationError
import java.util.ServiceLoader

fun loadAll(): List<Plugin> {
    val result = mutableListOf<Plugin>()
    val iterator = ServiceLoader.load(Plugin::class.java).iterator()
    while (true) {
        try {
            if (!iterator.hasNext()) break
            result += iterator.next()
        } catch (e: ServiceConfigurationError) {
            System.err.println("skipping plugin: ${e.message}")
        }
    }
    return result
}

The JDK documents recovery after an error as "best effort", so treat this as damage control, not a guarantee.

Project layout with Gradle

Put the API in its own small module. The host and every plugin depend on it, but plugins never depend on the host:

plugin-demo/
  settings.gradle.kts
  build.gradle.kts
  plugin-api/      interfaces only: Plugin, PluginContext, ...
  app/             the host
  plugins/upper/   one plugin per module
// settings.gradle.kts
rootProject.name = "plugin-demo"
include("plugin-api", "app", "plugins:upper")
// build.gradle.kts (root)
plugins {
    kotlin("jvm") version "2.4.21" apply false
}
// plugins/upper/build.gradle.kts
plugins {
    kotlin("jvm")
}

dependencies {
    // the host provides the API at runtime, don't bundle it
    compileOnly(project(":plugin-api"))
}
// app/build.gradle.kts
plugins {
    kotlin("jvm")
    application
}

dependencies {
    implementation(project(":plugin-api"))
    // built-in plugins can simply be on the runtime classpath
    runtimeOnly(project(":plugins:upper"))
}

application {
    mainClass = "com.example.app.MainKt"
}

compileOnly matters for plugins that are loaded from separate JAR files: if a plugin JAR contained its own copy of com.example.api.Plugin, a class loader could load it twice and the host would see two unrelated Plugin types, which fails with ClassCastException or makes ServiceLoader silently ignore the plugin. See Gradle configuration for more about Gradle builds.

Loading plugin JARs at runtime

To let users drop JAR files into a plugins/ directory, create a URLClassLoader for each JAR and pass it to ServiceLoader.load:

import com.example.api.Plugin
import java.net.URLClassLoader
import java.nio.file.Path
import java.util.ServiceLoader
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name

class LoadedPlugin(val plugin: Plugin, val loader: URLClassLoader, val jar: Path)

fun loadPluginJars(dir: Path): List<LoadedPlugin> =
    dir.listDirectoryEntries("*.jar").sorted().flatMap { jar ->
        val loader = URLClassLoader(
            "plugin-${jar.name}",              // name shows up in stack traces
            arrayOf(jar.toUri().toURL()),
            Plugin::class.java.classLoader,    // parent: sees the API classes
        )
        val found = ServiceLoader.load(Plugin::class.java, loader).stream()
            .filter { it.type().classLoader === loader } // only this JAR's plugins
            .map { LoadedPlugin(it.get(), loader, jar) }
            .toList()
        if (found.isEmpty()) loader.close()
        found
    }

fun main() {
    val host = PluginHost()
    val loaded = loadPluginJars(Path.of("plugins"))
    for (p in loaded) {
        host.load(p.plugin)
        println("${p.plugin.id} from ${p.jar.name}")
    }
}

Points that are easy to get wrong:

Unloading

To unload a plugin, stop it, close its class loader and drop every reference to its objects (including lambdas it registered):

fun unload(p: LoadedPlugin) {
    p.plugin.stop()
    p.loader.close() // releases the open JAR file
}

Classes are only unloaded after the garbage collector finds no references to the loader, any of its classes, or any instance of them. A single leftover reference (a registered listener, a thread started by the plugin, a ThreadLocal) keeps the whole plugin in memory. On Windows, the JAR file also stays locked until the loader is closed, so replacing a plugin file requires unloading first.

The thread context class loader

Some libraries look up classes through Thread.currentThread().contextClassLoader instead of their own loader (JDBC drivers, some serialization and logging libraries, ServiceLoader.load(Class) without a loader argument). When such code runs inside a plugin, it can't see the plugin's classes. Set the context loader while calling into the plugin:

inline fun <T> withClassLoader(loader: ClassLoader, block: () -> T): T {
    val thread = Thread.currentThread()
    val previous = thread.contextClassLoader
    thread.contextClassLoader = loader
    try {
        return block()
    } finally {
        thread.contextClassLoader = previous
    }
}

// withClassLoader(p.loader) { host.load(p.plugin) }

Versioning the API

Plugins are compiled against one version of your API and may run against another. Two techniques keep this manageable.

Add, don't change. New interface members get a default implementation, so plugins compiled against the old interface still work. Kotlin compiles interface methods with bodies to JVM default methods, so an old plugin class that doesn't implement the new method picks up the default. Removing a method or changing a signature breaks old plugins with AbstractMethodError or NoSuchMethodError when they are called.

Record the version a plugin was built against. A const val is inlined into the code that uses it at compile time, so a plugin that returns PLUGIN_API_VERSION reports the version it was compiled with, not the version of the host it runs in:

// in plugin-api
const val PLUGIN_API_VERSION = 3
const val MIN_PLUGIN_API_VERSION = 2

interface Plugin {
    val id: String
    val apiVersion: Int
    fun start(context: PluginContext)
    fun stop() {}
}

// in a plugin
class UpperPlugin : Plugin {
    override val id = "upper"
    override val apiVersion = PLUGIN_API_VERSION // inlined: stays 3 forever
    override fun start(context: PluginContext) { /* ... */ }
}

Isolating plugin failures

A plugin is code you didn't write. A bug in it shouldn't take down the host. Check the version, catch exceptions from lifecycle methods, and also catch LinkageError, which the JVM throws when a plugin was compiled against classes that changed:

fun PluginHost.loadSafely(plugin: Plugin): Boolean {
    if (plugin.apiVersion !in MIN_PLUGIN_API_VERSION..PLUGIN_API_VERSION) {
        println("skipping ${plugin.id}: built for API ${plugin.apiVersion}")
        return false
    }
    return try {
        load(plugin)
        true
    } catch (e: Exception) {
        println("plugin ${plugin.id} failed to start: ${e.message}")
        false
    } catch (e: LinkageError) {
        println("plugin ${plugin.id} is incompatible: $e")
        false
    }
}

class OldPlugin : Plugin {
    override val id = "old"
    override val apiVersion = 1
    override fun start(context: PluginContext) {}
}

class ClashingPlugin : Plugin {
    override val id = "clash"
    override val apiVersion = PLUGIN_API_VERSION
    override fun start(context: PluginContext) {
        context.registerCommand("sum") { "not the real sum" }
    }
}

fun main() {
    val host = PluginHost()
    host.loadSafely(MathPlugin()) // MathPlugin now also declares apiVersion = PLUGIN_API_VERSION
    host.loadSafely(OldPlugin())
    host.loadSafely(ClashingPlugin())
    println(host.execute("sum 2 3"))
}
[math] registered 2 commands
skipping old: built for API 1
plugin clash failed to start: 'sum' is already registered by math
5

Apply the same protection when the host calls plugin code later (command handlers, event listeners): wrap each call, log the failure with the plugin id, and consider disabling a plugin that keeps failing. A plugin that fails halfway through start() may already have registered some things; a robust host records registrations per plugin id (as the context above does) so it can remove them.

Plugins run with the same permissions as the host: they can read files, open sockets and call System.exit. The JDK's SecurityManager, which used to sandbox such code, is permanently disabled since Java 24. Only load plugins you trust, or run untrusted ones in a separate process and talk to them over a socket or pipes.

Configurable plugins with a type-safe install DSL

Ktor installs plugins with install(Plugin) { config }, and application.plugin(Plugin) returns the installed instance. The pattern combines a companion object as the plugin key, a configuration class and a lambda with receiver. Here is a minimal version:

class AttributeKey<T : Any>(val name: String)

interface AppPlugin<C : Any, P : Any> {
    val key: AttributeKey<P>
    fun install(app: App, configure: C.() -> Unit): P
}

class App {
    private val installed = mutableMapOf<AttributeKey<*>, Any>()
    val requestHandlers = mutableListOf<(String) -> Unit>()

    fun <C : Any, P : Any> install(plugin: AppPlugin<C, P>, configure: C.() -> Unit = {}): P {
        require(plugin.key !in installed) { "${plugin.key.name} is already installed" }
        val instance = plugin.install(this, configure)
        installed[plugin.key] = instance
        return instance
    }

    @Suppress("UNCHECKED_CAST")
    fun <P : Any> plugin(plugin: AppPlugin<*, P>): P =
        installed[plugin.key] as? P ?: error("${plugin.key.name} is not installed")

    fun handle(path: String) = requestHandlers.forEach { it(path) }
}

class RequestCounter(val label: String) {
    var count = 0
        private set

    class Config {
        var label = "requests"
    }

    companion object Plugin : AppPlugin<Config, RequestCounter> {
        override val key = AttributeKey<RequestCounter>("RequestCounter")

        override fun install(app: App, configure: Config.() -> Unit): RequestCounter {
            val config = Config().apply(configure)
            val counter = RequestCounter(config.label)
            app.requestHandlers.add { counter.count++ }
            return counter
        }
    }
}

fun main() {
    val app = App()
    app.install(RequestCounter) { label = "hits" }

    app.handle("/")
    app.handle("/about")

    val counter = app.plugin(RequestCounter)
    println("${counter.label}: ${counter.count}")
}
hits: 2

RequestCounter used as an expression refers to its companion object, which is why install(RequestCounter) reads like installing the class. The generic parameters tie everything together: the configuration lambda gets a Config receiver, and app.plugin(RequestCounter) returns a RequestCounter without a cast at the call site. count++ works inside the companion because a companion object can access private members of its class.

For real Ktor plugins (createApplicationPlugin, onCall, onCallRespond) see HTTP middleware.

Plugins vs. extension functions

Not every "extension" needs a plugin system. If you only want callers to add operations to your types, Kotlin extension functions already do that at compile time, with no registration or discovery:

// in any module that depends on the library
fun PluginHost.executeAll(vararg lines: String): List<String> = lines.map { execute(it) }

Extension functions can't change existing behavior and can't be discovered at runtime: the host doesn't know they exist. Use a plugin system when the host must find and call code it doesn't know about at compile time; use extension functions when the caller knows exactly what it wants to call.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents