Merge pull request #831 from ebersb/issue/url_builder

Prevent to set URL.factory to null in case of concurrent URL creation…
pull/836/head
Nikita Koksharov 8 years ago committed by GitHub
commit e1b54f0787

@ -23,6 +23,7 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLStreamHandler; import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* *
@ -32,6 +33,7 @@ import java.net.URLStreamHandlerFactory;
public class URLBuilder { public class URLBuilder {
private static URLStreamHandlerFactory currentFactory; private static URLStreamHandlerFactory currentFactory;
private static AtomicInteger refCounter = new AtomicInteger();
private final static URLStreamHandlerFactory newFactory = new URLStreamHandlerFactory() { private final static URLStreamHandlerFactory newFactory = new URLStreamHandlerFactory() {
@Override @Override
@ -63,28 +65,28 @@ public class URLBuilder {
}; };
public static synchronized void restoreURLFactory() { public static synchronized void restoreURLFactory() {
if (refCounter.decrementAndGet() == 0) {
try { try {
Field field = URL.class.getDeclaredField("factory"); Field field = URL.class.getDeclaredField("factory");
field.setAccessible(true); field.setAccessible(true);
field.set(null, currentFactory); field.set(null, currentFactory);
currentFactory = null;
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }
}
public static synchronized void replaceURLFactory() { public static synchronized void replaceURLFactory() {
try { try {
refCounter.incrementAndGet();
Field field = URL.class.getDeclaredField("factory"); Field field = URL.class.getDeclaredField("factory");
field.setAccessible(true); field.setAccessible(true);
currentFactory = (URLStreamHandlerFactory) field.get(null); final URLStreamHandlerFactory temp = (URLStreamHandlerFactory) field.get(null);
if (currentFactory != null && currentFactory != newFactory) { if (temp != newFactory) {
currentFactory = temp;
field.set(null, null); field.set(null, null);
}
if (currentFactory != newFactory) {
URL.setURLStreamHandlerFactory(newFactory); URL.setURLStreamHandlerFactory(newFactory);
} else {
currentFactory = null;
} }
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);

Loading…
Cancel
Save