Reputation: 3316
In Java documentation for a static method URL.setURLStreamHandlerFactory, there is a warning that "This method can be called at most once in a given Java Virtual Machine".
I briefly looked at the source code, and there is a one static instance variable in URL class:
static URLStreamHandlerFactory factory;
and setURLStreamHandlerFactory is merely assigning the factory to this variable:
public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) {
synchronized (streamHandlerLock) {
if (factory != null) {
throw new Error("factory already defined");
}
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
handlers.clear();
factory = fac;
}
}
Allowing this method to be called multiple times would result in overwriting this factory instance variable, but I don't see WHY Java would want to prevent this behavior.
WHY does Java require that this method can be called only once per JVM?
Upvotes: 6
Views: 459
Reputation: 2178
There seem to be no precise reason.
Interestingly, the Eclipse "Runnable JAR File Exporter" functionality registers a custom URLStreamHandlerFactory
named RsrcURLStreamHandlerFactory
.
URLStreamHandlerFactory
itself wraps an other URLStreamHandlerFactory
and provides a method setURLStreamHandlerFactory
to overwrite it. Quoting from the method's docs:
Allow one other URLStreamHandler to be added. URL.setURLStreamHandlerFactory does not allow multiple factories to be added. The chained factory is called for all other protocols, except "rsrc". Use null to clear previously set Handler.
This setURLStreamHandlerFactory
can be called multiple times and should provide some evidence of the fact that changing the handler should not cause any strange behaviour.
Even more Interestingly, I spotted a 1998 JDK feature request on the fact that setURLStreamHandlerFactory
should be allowed to be called multiple times so that several handlers could be chained together. The feature request was resolved as Future Project but evidently was never implemented.
Upvotes: 5