Disclaimer: This is probably not the best solution given the issue, but I'm curious how this implementation could be achieved.
Problem I'm trying to deal with some legacy code which has a singleton defined like bellow:
public class LegacySingleton {
private static Boolean value;
public static void setup(boolean v) {
if (value != null) {
throw new RuntimeException("Already Set up");
}
value = v;
System.out.println("Setup complete");
}
public static void teardown() {
value = null;
System.out.println("Teardown complete");
}
public static boolean getValue() {
return value;
}
}
I do not have the ability to change this design and the class is used heavily throughout the code base. The values returned by this singleton can greatly change the functionality of the code. Eg:
public class LegacyRequestHandler {
public void handleRequest() {
if (LegacySingleton.getValue()) {
System.out.println("Path A");
} else {
System.out.println("Path B");
}
}
}
Right now if I want the code to take Path A
, then I have to initialize LegacySingleton
in a particular way. If I then want to take Path B
I have to re-initialize the LegacySingleton
. There is no way of handling requests in parallel which take different paths; meaning for each different configuration of LegacySingleton
required I need to launch a separate JVM instance.
My Question Is it possible to isolate this singleton using separate class loaders? I've been playing around with the ClassLoader
API, but I cant quite figure it out.
I'm imagining it would look something along the lines of this:
public class LegacyRequestHandlerProvider extends Supplier<LegacyRequestHandler> {
private final boolean value;
public LegacyRequestHandlerProvider(boolean value) {
this.value = value;
}
@Override
public LegacyRequestHandler get() {
LegacySingleton.setup(value);
return new LegacyRequestHandler();
}
}
...
ClassLoader loader1 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier1 = loader1
.loadClass("com.project.LegacyRequestHandlerProvider")
.getConstructor(Boolean.TYPE)
.newInstance(true);
ClassLoader loader2 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier2 = loader2
.loadClass("com.project.LegacyRequestHandlerProvider")
.getConstructor(Boolean.TYPE)
.newInstance(false);
LegacyRequestHandler handler1 = supplier1.get();
LegacyRequestHandler handler2 = supplier2.get();