Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

with — service providers in a module

In Java SE 21, `with` is a contextual keyword in the `provides` directive of a module declaration. It separates the service type from its provider list; outside that context, it can be an identifier.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

provides ServiceType with ProviderType [, OtherProviderType ...];

with is a contextual, not an unconditionally reserved, keyword. In a provides directive in module-info.java, it introduces the service provider list. Outside its keyword context, a declaration such as int with = 1; is valid.

In provides ServiceType with ProviderType;, the left side identifies the service and the right side identifies its provider for ServiceLoader. Multiple providers can be separated by commas, without duplicates. Providers must be declared in the same module.

The example uses the constructor-based form: Task is a public class implementing Runnable with a public no-argument constructor. Another form uses a public static no-argument provider() method returning a subtype of the service; in that case, the provider itself need not be a subtype.

provides ... with ... declares a provider, whereas uses declares service consumption. The example module performs both roles. This description targets Java SE 21; production-runtime compatibility has not been attested.

Examples

// src/module-info.java
module demo.app {
    uses java.lang.Runnable;
    provides java.lang.Runnable with demo.Task;
}

// src/demo/Task.java
package demo;

public class Task implements Runnable {
    public Task() {}

    @Override
    public void run() {
        System.out.println("OK");
    }
}

// src/demo/Main.java
package demo;

import java.util.ServiceLoader;

public class Main {
    public static void main(String[] args) {
        ServiceLoader.load(Runnable.class)
                .findFirst()
                .orElseThrow()
                .run();
    }
}

Result

OK

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources