phil91
phil91

Reputation: 81

Class loaders and Service Loader. Which class loader is used?

I am working on writing an extensible application.

Reading the documentation about the ServiceLoader utility class, I was not able to understand the following sentence:

The provider must be accessible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.

Could anyone explain to me what does it mean?

How could I determine which class loader it is used to locate the configuration file?

Upvotes: 1

Views: 956

Answers (1)

John Bollinger
John Bollinger

Reputation: 180181

Could anyone explain to me what does it mean?

I think it is referring to the fact that ClassLoaders can and do perform delegation. If I perform, say,

MyClass.class.getClassLoader().getResource("/services/org/my/Service");

to find the configuration file, then it may be that the ClassLoader for MyClass delegates to a parent ClassLoader, and maybe that one to its parent, etc. so that it is not the ClassLoader I queried (MyClass.class.getClassLoader()) that actually loads the config file.

In that case, the specification says that no matter which ClassLoader actually locates the config file, the service classes it names must be accessible from MyClass.class.getClassLoader(). I take "accessible" here not to preclude its own delegation.

In practice, these provisions are probably more remarkable for ClassLoader implementations that follow more interesting strategies than simple delegation up a chain of ClassLoaders, as may be found in JavaEE containers, for example.

How could I determine which class loader it is used to locate the configuration file?

Generally speaking, you probably do not need to do so. I would recommend as a best strategy that you ensure that the service classes named by any given service configuration file are all accessible via (all) the same ClassLoaders as the config file itself. Putting them in the same jar should accomplish this, for instance.

Upvotes: 2

Related Questions