https://www.youtube.com/watch?v=4mT7qPMLkYE

With the introduction of modules in Java 9, it became possible to define clearly what libraries could be exported and which were for internal use. Modules can take care of the needs of 99 percent of the software architectures.

However, when writing plugins, it becomes necessary to load libraries that can deal with security limitations dynamically. This is where ServiceLoader comes in handy.

The ServiceLoader

The ServiceLoader was introduced in Java 1.6 and rewritten in Java 9. The ServiceLoader’s primary task is to broker code with interface implementation.

The ServiceLoader will attempt to load all SoftDrink implementations available on the classpath in the following example.

var softDrinks = ServiceLoader.load(SoftDrink.class);

for (var softDrink : softDrinks) {
	... // print soft Drink returned
}

Lazy Loading And Reloading

The loading of implementations by the ServiceLoader is lazy.

The objects will not be instantiated until needed, i.e., another method is invoked on that object.

Once instantiated, however, the object remains cached.

The cache can be cleared and objects reloaded as follows -

softDrinks.reload();

Constructors And ServiceLoader

ServiceLoader requires that classes either

In the following example, a provider static method creates a default object.

public DietPepsi(int size) {
	...
}

public static DietPepsi provider() {
	return new DietPepsi(10);
}

Using ServiceLoader With Modules