Prevent to set URL.factory to null in case of concurrent URL creation in the URLBuilder.

pull/831/head
Björn-Ole Ebers 8 years ago
parent 94fcfd5eae
commit 817bf0a2e2

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

Loading…
Cancel
Save