Why does Java require "This method can be called no more than once in a given Java virtual machine"?

There is a warning in the Java documentation for the static method URL.setURLStreamHandlerFactory that "this method can be called no more than 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 reviewed the source code and there is one static instance variable in the URL class:

static URLStreamHandlerFactory factory; 

and setURLStreamHandlerFactory just sets 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 will overwrite this factory instance variable, but I cannot see why Java wants to prevent this behavior.

WHY does Java require this method to be called only once in the JVM?

+6
source share
1 answer

There seems to be no exact reason.

Interestingly, the Eclipse "Runnable JAR File Exporter" functionality registers a custom URLStreamHandlerFactory named RsrcURLStreamHandlerFactory . URLStreamHandlerFactory itself carries another URLStreamHandlerFactory and provides a setURLStreamHandlerFactory method to overwrite it. Quoting from the docs method:

Allow the addition of another URLStreamHandler. URL.setURLStreamHandlerFactory does not allow multiple plants to be added. A chained factory is invoked for all other protocols except rsrc. Use null to clear a previously defined handler.

This setURLStreamHandlerFactory can be called multiple times and should provide some evidence that changing the handler should not cause any strange behavior.

Even more interestingly, I noticed a JDK function request that setURLStreamHandlerFactory should be allowed to be called multiple times so that multiple handlers can be connected together. The function request was resolved as a future project, but apparently was never implemented.

+5
source

Source: https://habr.com/ru/post/989637/


All Articles