Enhanced ServiceLoader?

Tim Boudreau niftiness at gmail.com
Tue Mar 10 03:23:32 UTC 2015


>
> > NetBeans did the ordering hints for years by enhancing META-INF/services
> > files with magic comments, e.g.
> >
> > #position 1000
> > com.foo.Bar
> >
> > It would be good if ServiceLoader could grow enough heft to handle that
> > role - not necessarily identically - but the feature satisfies a proven
> > need.
>
> How is this any different than an @Ordered annotation?


It isn't, other than that as a performance optimization, you don't have to
load the class to determine its order.


>   Doesn't it still
> assume that the author of a module somehow has global knowledge of how
> that module will be used in every possible scenario?
>

It assumes the author of a module has at least *partial* knowledge of how
that module will be used in its *intended* scenario:

/**
* Foos are ordered from Integer.MIN_VALUE to Integer.MAX_VALUE.  More
* expensive-to-run Foos should be placed close to last.
*/
public class Foo { ... }

@ServiceProvider(service=Foo.class, position=Integer.MIN_VALUE)
public class CheapFoo { ... }

@ServiceProvider(service=Foo.class, position=0)
public class MediumFoo { ... }

@ServiceProvider(service=Foo.class, position=Integer.MAX_VALUE)
public class ReallyExpensiveFoo { ... }

An application is free to use these in some alternate order if its scenario
is in fact not the intended scenario.

Since the API author has defined the bounds and the meaning of the low and
high bounds, the API implementer does not need global knowledge, only
knowledge about one or more other implementations.

While it is possible for that knowledge to be wrong - there might be an
UberExpensiveFoo that should definitely come after ReallyExpensiveFoo -
most of the time people are not operating with a total lack of knowledge of
the environment their code will run in, so having an order provides quite a
bit of value.  If there is really something that does have a global view,
it is free to ignore the hinted order.

I've seen code be accidentally dependent on listener order (this is, in
fact, why you can't change Swing Look and Feels without a restart in
NetBeans - it reorders look and feel listeners to be called after
application listeners, and finding all the sites where that assumption was
accidentally made and preventing new ones is a near impossibility).  I've
seen it happen with service registration order too.

In general, if you're going to have an API that purports to provide an
"unordered" collection, sooner or later someone is going to inadvertently
depend on the order they encounter at runtime - and service registrations
are definitely things where that's likely.  So in the interest of people
writing less-likely-to-fail code, having a way to make that order explicit
is a good thing.

-Tim

-- 
http://timboudreau.com


More information about the jpms-spec-experts mailing list