Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java require "This method can be called at most once in a given Java Virtual Machine"?

Tags:

java

jvm

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".

http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)

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?

like image 318
SHH Avatar asked Jun 23 '15 18:06

SHH


1 Answers

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.

like image 168
mziccard Avatar answered Nov 10 '22 00:11

mziccard